  //
//  Data_Object.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/2/13.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//

#import "Data_Object.h"
#import "Data_Model.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBCalculationMethod_commonIndicator.h"
#import "GBCalculationMethod_selfIndicator.h" 
#import "GBTableColumnHeader_key.h"
#import "GBall.h"
#import "RSworkSheet.h"
#import "RSworkBook.h"
#import "RSworkSheetRow.h"

@implementation Data_Object
 
@synthesize table_data;
@synthesize his_data_get_date;
@synthesize his_data_high,his_data_low;
@synthesize data_object_para;



- (id)init_data:(NSMutableDictionary *)dic_data datamodel:(Data_Model *)dm _calculate_property_all:(NSMutableDictionary *)_calculate_property_all{
	
    if(self=[super init])
	{
         
        delgete_m=dm;
        
        table_data=[dic_data retain];
       
        his_data_serial=nil;
        
        //初始參數物件
        
        DMPara *dmp= [[DMPara alloc] init_code:[table_data objectForKey:DB_object_sqlite_basic_code] database_path:[dm databasePath_nsame] _calculate_property_all:_calculate_property_all]  ;
       
        [self setData_object_para:dmp];
      
        [dmp release];
        
        
        
        //歷史資料暫存檔案目錄路徑
        {
            NSString *code=[table_data objectForKey:DB_object_sqlite_basic_code];
            //歷史檔案路徑
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
            NSString *Path_HistoryData_catches  ; 
            Path_HistoryData_catches=[prefs objectForKey:Defaults_Path_HistoryData_Catches];    
            
            NSString *filename_plist;
            filename_plist=[NSString stringWithFormat: @"%@.plist",code];
            NSString * write_FilepathnName_plist= [Path_HistoryData_catches stringByAppendingPathComponent:filename_plist]  ;             
            Path_history_serial_write_to_catch_plist = [ write_FilepathnName_plist retain];   
           
            NSString *filename_arch;
            filename_arch=[NSString stringWithFormat: @"%@.arch",code];
            NSString * write_FilepathnName_arch= [Path_HistoryData_catches stringByAppendingPathComponent:filename_arch]  ;             
            Path_history_serial_write_to_catch_arch = [ write_FilepathnName_arch retain];   
            
        
        }
        
    
    }
	
	return self;
}

#pragma mark -
#pragma mark 歷史資料序列存取

-(void)save_calcuate_his_data_serial:(NSMutableArray *)hisDa
               reforce_calculate_all:(BOOL)reforce_calculate_all
                       delgete_model:(Data_Model *)delgete_model{
       
    //reforce_calculate_all 參數意義:是否強迫全部重新計算
   
    //先取出是否要用調整收盤價當作收盤價
    {
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        isUseAdjClose=[[prefs objectForKey:Defaults_isUse_AdjClose] boolValue];
    }
    
    //設定資料庫委托位置
    delgete_m=delgete_model;
    
    //取出必須計算的方法
    NSMutableArray *have_Calculate_method;
    have_Calculate_method=[(Data_Model * )delgete_m  have_to_calculate_history_serial_indicator_signal];
    
         
    int start_index; //循環起始位置
    int back_index;  //往前推第幾天之後開始計算
    back_index=1;    //假設往前推1天計算 但是如果使用者超過三天沒有超過計算則有可能少算錯誤
    
   
    if (hisDa) {
        
        //1.判斷計算的開始位置        
        if ([hisDa count]>0) {
            //傳入的資料正常且
            
            int check_index;
            check_index=[hisDa count]-1-1;  //檢查是否已經有計算過位置 倒數前ㄧ個 因為最後一個可能更新過報價所以一定沒有計算過的痕跡,所以是以倒數第一個位置來檢查           
           
            if (reforce_calculate_all==YES) {
               //強迫全部重新計算 
                 
                start_index=0;
                
                //NSLog(@"重新計算所有歷史資料序列計算=%@ ", [table_data objectForKey:DB_object_sqlite_basic_code]  );
                //強迫將計算的數據清除
                for (int i=start_index; i <= [hisDa count]-1; i++) {
                    NSMutableDictionary *his_dic=[hisDa objectAtIndex:i];
                    
                    [his_dic removeObjectForKey:HIS_dic_indicator];
                    [his_dic removeObjectForKey:HIS_dic_signal];
                    [his_dic removeObjectForKey:HIS_dic_profit];
                    [his_dic removeObjectForKey:HIS_dic_temp];                    
                }                
                
            }
            else {
               //判斷需要重新計算或是依照有計算內容計算
                if ([hisDa count]>=2) {
                    //數量至少要大於2
                    
                    if ([[hisDa objectAtIndex:check_index] objectForKey:HIS_dic_indicator] && [[hisDa objectAtIndex:check_index] objectForKey:HIS_dic_signal] && [[hisDa objectAtIndex:check_index] objectForKey:HIS_dic_profit] && [[hisDa objectAtIndex:check_index] objectForKey:HIS_dic_temp]) {
                        
                        //表示傳入的hisData 的最後一筆陣列內容含有計算痕跡 ＝>所以就進行最後一筆重新計算
                        
                        start_index=[hisDa count]-1-back_index; //往前推幾天之後開始計算
                        if (start_index<0) {
                            start_index=0;
                        }
                        
                        
                    }
                    else {
                        //表示無最後一筆計算痕跡全部重頭計算
                        start_index=0;                
                    }                
                    
                    
                }
                else {
                    //表示無最後一筆計算痕跡全部重頭計算
                    start_index=0;
                }
            }
                                   
        }
        else {
            start_index=0;
        } 
        
        //最低K線數量開始計算
        int min_kbar_MESA;
        min_kbar_MESA=10;
               
        //2.計算指標與訊號  
        for (int i=start_index; i <= [hisDa count]-1; i++) {
            
            //1.記憶體暫存區 
            
            //a.取出本期歷史資料序列的基本資料 
            NSMutableDictionary *his_dic=[hisDa objectAtIndex:i];
            
            //b.初始化與實體化 計算暫存字典
            NSMutableDictionary *dic_indicator; //指標數值
            NSMutableDictionary *dic_signal;    //訊號數值
            NSMutableDictionary *dic_profit;    //訊號數值
            NSMutableDictionary *dic_temp;      //暫存檔
            
            dic_indicator=[[NSMutableDictionary alloc] init];
            dic_signal=[[NSMutableDictionary alloc] init];        
            dic_temp=[[NSMutableDictionary alloc] init];  
            dic_profit=[[NSMutableDictionary alloc] init];              
                              
            
            //2.計算區
            //標記：加入一個計算方法 2.實作計算            
            {
                //標記：買賣訊號 2.實作計算
                //標記：技術指標 2.實作計算
                {
                    
                    //MA
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_MA]==NSNotFound) ) {
                       
                        [self  calculateFunction_MA:Defaults_Calculate_MA
                                             fhisDa:hisDa
                                              index:i
                                     fdic_indicator:dic_indicator
                                        fdic_signal:dic_signal
                                          fdic_temp:dic_temp
                                        fdic_profit:dic_profit];                          
                    }
                    
                    //KD
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_KD]==NSNotFound) ) {
                        
                        [self  calculateFunction_KD:Defaults_Calculate_KD
                                             fhisDa:hisDa
                                              index:i
                                     fdic_indicator:dic_indicator
                                        fdic_signal:dic_signal
                                          fdic_temp:dic_temp
                                        fdic_profit:dic_profit];                         
                        
                    }
                    
                    //MACD
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_MACD]==NSNotFound) ) {
                        
                        [self  calculateFunction_MACD:Defaults_Calculate_MACD
                                               fhisDa:hisDa
                                                index:i
                                       fdic_indicator:dic_indicator
                                          fdic_signal:dic_signal
                                            fdic_temp:dic_temp
                                          fdic_profit:dic_profit];
                        
                        
                    }
                    //VOL
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_VOL]==NSNotFound) ) {
                        
                    }
                    
                    
                    //LF
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_LF1]==NSNotFound) ) {
                        
                        [self  calculateFunction_LF:Defaults_Calculate_LF1
                                               fhisDa:hisDa
                                                index:i
                                       fdic_indicator:dic_indicator
                                          fdic_signal:dic_signal
                                            fdic_temp:dic_temp
                                          fdic_profit:dic_profit];
                        
                        
                    }     
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_LF2]==NSNotFound) ) {
                        
                        [self  calculateFunction_LF:Defaults_Calculate_LF2
                                             fhisDa:hisDa
                                              index:i
                                     fdic_indicator:dic_indicator
                                        fdic_signal:dic_signal
                                          fdic_temp:dic_temp
                                        fdic_profit:dic_profit];
                        
                    }                       
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_LF3]==NSNotFound) ) {
                        
                        [self  calculateFunction_LF:Defaults_Calculate_LF3
                                             fhisDa:hisDa
                                              index:i
                                     fdic_indicator:dic_indicator
                                        fdic_signal:dic_signal
                                          fdic_temp:dic_temp
                                        fdic_profit:dic_profit];
                        
                    }
                    
                    //LFMESA
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_LFMESA1]==NSNotFound) ) {
                        
                        [self  calculateFunction_LFMESA:Defaults_Calculate_LFMESA1
                                                     fhisDa:hisDa
                                                      index:i
                                             fdic_indicator:dic_indicator
                                                fdic_signal:dic_signal
                                                  fdic_temp:dic_temp
                                                fdic_profit:dic_profit];
                        
                        
                    }
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_LFMESA2]==NSNotFound) ) {
                        
                        [self  calculateFunction_LFMESA:Defaults_Calculate_LFMESA2
                                                     fhisDa:hisDa
                                                      index:i
                                             fdic_indicator:dic_indicator
                                                fdic_signal:dic_signal
                                                  fdic_temp:dic_temp
                                                fdic_profit:dic_profit];
                        
                    }
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_LFMESA3]==NSNotFound) ) {
                        
                        [self  calculateFunction_LFMESA:Defaults_Calculate_LFMESA3
                                                     fhisDa:hisDa
                                                      index:i
                                             fdic_indicator:dic_indicator
                                                fdic_signal:dic_signal
                                                  fdic_temp:dic_temp
                                                fdic_profit:dic_profit];
                        
                    }
                    
                    //MESA
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_MESA1]==NSNotFound) ) {
                       
                        if (i>min_kbar_MESA) {
                             [self  calculateFunction_MESA:Defaults_Calculate_MESA1 fhisDa:hisDa index:i fdic_indicator:dic_indicator fdic_signal:dic_signal fdic_temp:dic_temp fdic_profit:dic_profit];
                        }
                                              
                        
                    }                       
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_MESA2]==NSNotFound) ) {
                        
                        if (i>min_kbar_MESA) {
                            [self  calculateFunction_MESA:Defaults_Calculate_MESA2 fhisDa:hisDa index:i fdic_indicator:dic_indicator fdic_signal:dic_signal fdic_temp:dic_temp fdic_profit:dic_profit];
                        }
                         
                    }  
                    if (!([have_Calculate_method indexOfObject:Defaults_Calculate_MESA3]==NSNotFound) ) {
                        if (i>min_kbar_MESA) {
                            [self  calculateFunction_MESA:Defaults_Calculate_MESA3 fhisDa:hisDa index:i fdic_indicator:dic_indicator fdic_signal:dic_signal fdic_temp:dic_temp fdic_profit:dic_profit];
                        }
                         
                        
                    }
                    
                                       
                }            
            }
                       
            //3.計算數值放到dic暫存區上
            {
                //標記：買賣訊號 2.實作計算 儲存結果
                //標記：技術指標 2.實作計算 儲存結果          
                 
                [dic_temp setObject:[his_dic objectForKey:HIS_basic_close] forKey:DB_his_data_signal_serial_sample];
                
                      
            }
            
            //4.最後一筆計算結果存到暫存區
            if (i==[hisDa count]-1) {
                [last_dic_indicator release];
                last_dic_indicator=[dic_indicator retain];
                
                [last_dic_signal release];
                last_dic_signal=[dic_signal retain];
                
                [last_dic_profit release];
                last_dic_profit=[dic_profit retain];
                
                
                [last_dic_temp release];
                last_dic_temp=[dic_temp retain];
            }
            
            
            //5.將計算結果存到時間序列上
            {
                [his_dic setObject:dic_indicator forKey:HIS_dic_indicator];        
                [dic_indicator release];
                
                [his_dic setObject:dic_signal forKey:HIS_dic_signal];        
                [dic_signal release];        
                
                [his_dic setObject:dic_profit forKey:HIS_dic_profit];
                [dic_profit release];
                
                [his_dic setObject:dic_temp forKey:HIS_dic_temp];        
                [dic_temp release];        
            }
                       
        }    
           
        //3.清除暫存區的記憶體 此段程式很重要 可以減少記憶體使用
        {
            //將最近min_kbar_LF 的HIS_dic_temp 中的LF 資料刪除            
            //尚未處理
            
            //將最近min_kbar_MESA 的HIS_dic_temp 中的MESA 資料刪除
            int keep_bar_count=10;
            if ([hisDa count] > min_kbar_MESA+keep_bar_count) {
                for (int i=0; i <  [hisDa count]-1-min_kbar_MESA; i++){
                 
                    
                    //取出第幾個字典
                    NSMutableDictionary *his_dic=[hisDa objectAtIndex:i];
                    //取出HIS_dic_temp
                    NSMutableDictionary *his_dic_temp=[his_dic objectForKey:HIS_dic_temp];
                    
                    [his_dic_temp removeObjectForKey:Defaults_Calculate_MESA1];
                    [his_dic_temp removeObjectForKey:Defaults_Calculate_MESA2]; 
                    [his_dic_temp removeObjectForKey:Defaults_Calculate_MESA3];     
                    
                    
                    
                } 
            }
                 
        }
              
        
        //4.歷史資料與計算結果 存入硬碟或是放在記憶體
        {
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
            
            if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_plist  ]) {
                //方法：硬碟:plist
                [hisDa writeToFile:Path_history_serial_write_to_catch_plist atomically:YES];
            }
            else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_arch  ]){
                //方法：硬碟:arch        
                
                
                [NSKeyedArchiver archiveRootObject:hisDa toFile:Path_history_serial_write_to_catch_arch];         
                
                
            }        
            else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_Memory  ]){
                //方法：記憶體        
                if (his_data_serial !=hisDa) {
                    
                   // NSLog(@"重設或第ㄧ次設歷史資料序列 記憶體=%@", [table_data objectForKey:DB_object_sqlite_basic_code]);
                    [his_data_serial release];
                    his_data_serial=[hisDa retain];
                    
                }  
                else {
                   // NSLog(@"不重設或第ㄧ次設歷史資料序列 記憶體=%@", [table_data objectForKey:DB_object_sqlite_basic_code]);        
                }
                
            }
            
            
        }
        
        //輸出到excel上作檢查
        {             
            if (NO) {
               
                 NSLog(@"hisDa=%@",hisDa );
                
                
                
                //1.建立工作簿
                RSworkBook * excel_book = [ [RSworkBook alloc] init];
                excel_book.author = @"xxtradex";
                excel_book.version = 1.2;
                
                //1.建立工作表sheet
                RSworkSheet * sheet = [[RSworkSheet alloc] initWithName:@"明細"];
                [excel_book addWorkSheet:sheet];
                [sheet release];

                //3.標題列
                {
                    RSworkSheetRow * row_title = [[RSworkSheetRow alloc] initWithHeight:20];
                    //該列高度
                    row_title.height=20;
                    
                    //標題列cell 格式
                    RSStyle *cell_style_title ;
                    {
                        
                        cell_style_title = [[[RSStyle alloc] init] autorelease];
                        cell_style_title.font = [NSFont fontWithName:@"新細明體" size:14];
                        cell_style_title.size = 17;
                        cell_style_title.color = [NSColor redColor];
                        cell_style_title.alignmentH = RSStyleLeftAlign;
                        cell_style_title.alignmentV = RSStyleCenterAlign;
                        
                        //cell 框線格式
                        cell_style_title.gridlinestyle_Right=RSStyleGridContinuous;
                        cell_style_title.gridlinestyle_Left=RSStyleGridContinuous;
                        cell_style_title.gridlinestyle_Top=RSStyleGridContinuous;
                        cell_style_title.gridlinestyle_Bottom=RSStyleGridDouble;
                        
                        //cell 框線寬度 注意：最大值不可以超過3
                        cell_style_title.gridlinesWidth_Bottom=1;
                        cell_style_title.gridlinesWidth_Left=1;
                        cell_style_title.gridlinesWidth_Right=1;
                        cell_style_title.gridlinesWidth_Top=1;
                        
                        
                    }
                    
                    //該列內容
                    {
                        //cola:A
                        [row_title addCellString:@"日期" withStyle:cell_style_title];
                        
                        //cola:B
                        [row_title addCellString:@"收盤價" withStyle:cell_style_title];
                      
                        //cola:C
                        [row_title addCellString:@"開盤價" withStyle:cell_style_title];
                        
                        //cola:D
                        [row_title addCellString:@"多空狀態" withStyle:cell_style_title];
                        
                        //cola:E
                        [row_title addCellString:@"多空訊號" withStyle:cell_style_title];
                        
                        //cola:F
                        [row_title addCellString:@"停損" withStyle:cell_style_title];
                        
                        
                        //cola:G
                        [row_title addCellString:@"做多次數" withStyle:cell_style_title];
                        
                        //cola:H
                        [row_title addCellString:@"做空次數" withStyle:cell_style_title];
                        
                        //cola:I
                        [row_title addCellString:@"多出場" withStyle:cell_style_title];
                        
                        //cola:J
                        [row_title addCellString:@"空出場" withStyle:cell_style_title];
                        
                        //cola:K
                        [row_title addCellString:@"平均進場成本" withStyle:cell_style_title];
                        
                        //cola:L
                        [row_title addCellString:@"是否有加碼動作" withStyle:cell_style_title];
                        
                        //cola:M
                        [row_title addCellString:@"最後庫存部位多空" withStyle:cell_style_title];
                        
                        //cola:N
                        [row_title addCellString:@"單筆已經實現損益" withStyle:cell_style_title];
                        
                        //cola:O
                        [row_title addCellString:@"單筆未實現損益" withStyle:cell_style_title];
                        
                        
                    }
                    
                    [sheet addWorkSheetRow:row_title];
                    [row_title release];
                }
                
                //4.內容格式
                RSStyle *cell_style_content ;
                {
                    
                    cell_style_content = [[[RSStyle alloc] init] autorelease];
                    cell_style_content.font = [NSFont fontWithName:@"新細明體" size:14];
                    cell_style_content.size = 14;
                    cell_style_content.color = [NSColor redColor];
                    cell_style_content.alignmentH = RSStyleLeftAlign;
                    cell_style_content.alignmentV = RSStyleCenterAlign;
                    
                    //cell 框線格式
                    cell_style_content.gridlinestyle_Right=RSStyleGridContinuous;
                    cell_style_content.gridlinestyle_Left=RSStyleGridContinuous;
                    cell_style_content.gridlinestyle_Top=RSStyleGridContinuous;
                    cell_style_content.gridlinestyle_Bottom=RSStyleGridContinuous;
                    
                    //cell 框線寬度 注意：最大值不可以超過3
                    cell_style_content.gridlinesWidth_Bottom=1;
                    cell_style_content.gridlinesWidth_Left=1;
                    cell_style_content.gridlinesWidth_Right=1;
                    cell_style_content.gridlinesWidth_Top=1;
                    
                    
                }
                
                //1.sheet 工作
                {
                   
                    
                    
                    //該列內容
                    {
                        for (NSMutableDictionary *_dic in hisDa) {
                            
                            //NSLog(@"%@",[_dic objectForKey:HIS_basic_date]);
                            RSworkSheetRow * row_data = [[RSworkSheetRow alloc] initWithHeight:45];
                            row_data.height=20;
                            
                            //cola:A 日期
                             [row_data addCellString:[_dic objectForKey:HIS_basic_date]   withStyle:cell_style_content];
                            
                            
                            //cola:B 收盤價
                            [row_data addCellNumber: [[_dic objectForKey:HIS_basic_close] floatValue]   withStyle:cell_style_content];
                            
                            
                            //cola:C 開盤價
                            [row_data addCellNumber: [[_dic objectForKey:HIS_basic_open] floatValue]   withStyle:cell_style_content];
                            
                            //HIS_dic_signal
                            {
                                NSMutableDictionary *dic_HIS_dic_signal=[_dic objectForKey:HIS_dic_signal];
                                
                                //Defaults_Calculate_LFMESA1
                                {
                                 
                                    NSMutableDictionary *dic_HIS_dic_signal_Defaults_Calculate_LFMESA1=[dic_HIS_dic_signal objectForKey:Defaults_Calculate_LFMESA1];
                                
                                    
                                    //cola:D CL_his_data_signal_LFMESA1_State                                    
                                    [row_data addCellNumber: [[dic_HIS_dic_signal_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_signal_LFMESA1_State] floatValue]   withStyle:cell_style_content];
                                
                                
                                    //cola:E CL_his_data_signal_LFMESA1_BS
                                    [row_data addCellNumber: [[dic_HIS_dic_signal_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_signal_LFMESA1_BS] floatValue]   withStyle:cell_style_content];
                                    
                                    //cola:F CL_his_data_signal_LFMESA1_BS_Stop
                                    [row_data addCellNumber: [[dic_HIS_dic_signal_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_signal_LFMESA1_BS_Stop] floatValue]   withStyle:cell_style_content];
                                    
                                    
                                    
                                }
                                
                                
                                
                            }
                            
                            //HIS_dic_indicator
                            {
                                NSMutableDictionary *dic_HIS_dic_indicator=[_dic objectForKey:HIS_dic_indicator];
                                
                                //Defaults_Calculate_LFMESA1
                                {
                                    
                                    NSMutableDictionary *dic_HIS_dic_indicator_Defaults_Calculate_LFMESA1=[dic_HIS_dic_indicator objectForKey:Defaults_Calculate_LFMESA1];
                                    
                                    
                                    //cola:G CL_his_data_indicator_LFMESA1_Long_Step_Count
                                    [row_data addCellNumber: [[dic_HIS_dic_indicator_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_indicator_LFMESA1_Long_Step_Count] floatValue]   withStyle:cell_style_content];
                                    
                                    
                                    //cola:H CL_his_data_indicator_LFMESA1_Short_Step_Count
                                    [row_data addCellNumber: [[dic_HIS_dic_indicator_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_indicator_LFMESA1_Short_Step_Count] floatValue]   withStyle:cell_style_content];
                                    
                                    //cola:I CL_his_data_indicator_LFMESA1_Long_StopPrice
                                    [row_data addCellNumber: [[dic_HIS_dic_indicator_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_indicator_LFMESA1_Long_StopPrice] floatValue]   withStyle:cell_style_content];
                                    
                                    //cola:J CL_his_data_indicator_LFMESA1_Short_StopPrice
                                    [row_data addCellNumber: [[dic_HIS_dic_indicator_Defaults_Calculate_LFMESA1 objectForKey:CL_his_data_indicator_LFMESA1_Short_StopPrice] floatValue]   withStyle:cell_style_content];
                                    
                                    
                                    
                                }
                                
                                
                                
                            }
                            
                            //HIS_dic_temp
                            {
                                NSMutableDictionary *dic_HIS_dic_temp=[_dic objectForKey:HIS_dic_temp];
                                
                                //Defaults_Calculate_LFMESA1
                                {
                                    
                                    NSMutableDictionary *dic_dic_HIS_dic_temp_Defaults_Calculate_LFMESA1=[dic_HIS_dic_temp objectForKey:Defaults_Calculate_LFMESA1];
                                    
                                    
                                    //cola:K HIS_dic_temp_profit_enterprice_average
                                    [row_data addCellNumber: [[dic_dic_HIS_dic_temp_Defaults_Calculate_LFMESA1 objectForKey:HIS_dic_temp_profit_enterprice_average] floatValue]   withStyle:cell_style_content];
                                    
                                    
                                    //cola:L HIS_dic_temp_profit_long_add
                                    [row_data addCellNumber: [[dic_dic_HIS_dic_temp_Defaults_Calculate_LFMESA1 objectForKey:HIS_dic_temp_profit_long_add] intValue]   withStyle:cell_style_content];
                                    
                                    
                                    //cola:M HIS_dic_temp_profit_bs
                                    [row_data addCellNumber: [[dic_dic_HIS_dic_temp_Defaults_Calculate_LFMESA1 objectForKey:HIS_dic_temp_profit_bs] intValue]   withStyle:cell_style_content];
                                    
                                    //cola:N HIS_dic_temp_profit_single_realize
                                    [row_data addCellNumber: [[dic_dic_HIS_dic_temp_Defaults_Calculate_LFMESA1 objectForKey:HIS_dic_temp_profit_single_realize] floatValue]   withStyle:cell_style_content];
                                    
                                    //cola:O HIS_dic_temp_profit_single_unrealize
                                    [row_data addCellNumber: [[dic_dic_HIS_dic_temp_Defaults_Calculate_LFMESA1 objectForKey:HIS_dic_temp_profit_single_unrealize] floatValue]   withStyle:cell_style_content];
                                    
                                    
                                }
                                
                                
                                
                            }
                            
                            
                            
                            [sheet addWorkSheetRow:row_data];
                             [row_data release];
                        }
                        
                      
                        
                    }
                    
                   
                    
                }
                
                
                //6.存檔
                {
                    //存入路徑
                    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString *documentsDir = [documentPaths objectAtIndex:0];
                    
                    NSString *BundleIdentifier;
                    BundleIdentifier=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
                    
                    documentsDir=[documentsDir stringByAppendingPathComponent:BundleIdentifier];
                    
                    //寫入檔案
                    [excel_book writeWithName:@"測試使用" toPath:documentsDir];
                    [excel_book release];
                    
                    
                    
                }                
                
                
            }
        
        }
      
        
    }
    
        
}
 
-(NSMutableArray *) get_his_data_serial{
    
   // NSLog(@"從暫時檔案取出歷史資料序列=%@",[table_data objectForKey:DB_object_sqlite_basic_code]  );
    //將歷史資料取出方法
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
    
    if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_plist  ]) {
        //方法：硬碟:plist
        return  [NSMutableArray arrayWithContentsOfFile:Path_history_serial_write_to_catch_plist]  ;        
        
    }
    else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_arch  ]){
        //方法：硬碟:arch        
        return    [NSKeyedUnarchiver unarchiveObjectWithFile:Path_history_serial_write_to_catch_arch] ;
    
    
    }        
    else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_Memory  ]){
        //NSLog(@"aaa=%@",his_data_serial);
        
        //方法：記憶體
        return  his_data_serial  ;
        
    }
    else {
        return nil;
    }
        
}

//重新計算所有歷史資料序列計算
-(void)re_calculate_history_indicator_signal{
   
    NSMutableArray *hisd=[self get_his_data_serial];
    
    if (hisd) {
        //有資料內容
      
      // NSLog(@"重新計算所有歷史資料序列計算=%@", [table_data objectForKey:DB_object_sqlite_basic_code]);
       [self save_calcuate_his_data_serial:hisd reforce_calculate_all:YES delgete_model:delgete_m  ]; 
    
    }   
    else {
        
      //  NSLog(@"不重新計算所有歷史資料序列計算=%@", [table_data objectForKey:DB_object_sqlite_basic_code]);
    }
  
}
 
#pragma mark -
#pragma mark 計算方法函數

//MA 移動均線
-(void)calculateFunction_MA:(NSString *)calculate_key fhisDa:(NSMutableArray *)fhisDa index:(int)i fdic_indicator:(NSMutableDictionary *)fdic_indicator fdic_signal:(NSMutableDictionary *)fdic_signal fdic_temp:(NSMutableDictionary *)fdic_temp fdic_profit:(NSMutableDictionary *)fdic_profit{
   
    //開收高低基本資料
    double close;       
    NSMutableDictionary *his_dic=[fhisDa objectAtIndex:i];
    
    if (isUseAdjClose==YES) {
         close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue];
    }
    else{
         close=[[his_dic objectForKey:HIS_basic_close] doubleValue];
    }
    
                
           
    
    //宣告變數
    double indicator_MA_1,indicator_MA_2,indicator_MA_3,indicator_MA_4,indicator_MA_5;
    double indicator_MA_1_1,indicator_MA_2_1; //前一期            
    int MA_BS,MA_State;
    {
         
        MA_BS=0;
        MA_State=0;                           
    }                                 
    //參數
    int MA_day1,MA_day2,MA_day3,MA_day4,MA_day5;
    {
       // MA_day1=5;
       // MA_day2=20;
       // MA_day3=60;
       // MA_day4=120;
       // MA_day5=240;
        
        //取出參數存放位置字典
        NSString *DWM;
        NSMutableDictionary *para_dic_all  ;
        NSMutableDictionary *para_dic_all_method ;//取出特定方法下的參數值
        NSMutableDictionary *para_dic; //取出特定週期的參數值
        
        DWM=day; //!!!!!!! 很重要目前是以日線參數來進行計算
        
        para_dic_all=  [[self data_object_para] Para_calculate_method:calculate_key period:DWM]  ;
        
        para_dic_all_method=[para_dic_all objectForKey:calculate_key ];
        para_dic=[para_dic_all_method objectForKey:day];
        
         
        
        MA_day1   =[[para_dic objectForKey:Para_1] intValue];
        MA_day2   =[[para_dic objectForKey:Para_2] intValue];
        MA_day3   =[[para_dic objectForKey:Para_3] intValue];
        MA_day4   =[[para_dic objectForKey:Para_4] intValue];
        MA_day5   =[[para_dic objectForKey:Para_5] intValue];
        
    }                        
    
    //計算
    {
        //指標
        {
            //1
            if (i>=MA_day1) {
                double sum1;
                
                sum1=0;
                for (int j=0; j<MA_day1; j++) {
                    
                    
                    if (isUseAdjClose==YES) {
                       sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_adjclose] doubleValue];
                    }
                    else{
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_close] doubleValue];
                    }
                    
                }
                indicator_MA_1=sum1/MA_day1;
                
            }
            else {
                indicator_MA_1=close;
                
                
            }
            //2
            if (i>=MA_day2) {
                double sum1;
                
                sum1=0;
                for (int j=0; j<MA_day2; j++) {
                    
                    if (isUseAdjClose==YES) {
                       sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_adjclose] doubleValue];
                    }
                    else{
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_close] doubleValue];
                    }
                    
                    
                }
                indicator_MA_2=sum1/MA_day2;
                
            }
            else {
                indicator_MA_2=close;
                
                
            }
            
            //3
            if (i>=MA_day3) {
                double sum1;
                
                sum1=0;
                for (int j=0; j<MA_day3; j++) {
                    if (isUseAdjClose==YES) {
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_adjclose] doubleValue];
                    }
                    else{
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_close] doubleValue];
                    }
                }
                indicator_MA_3=sum1/MA_day3;
                
            }
            else {
                indicator_MA_3=close;
                
                
            }
            
            //4
            if (i>=MA_day4) {
                double sum1;
                
                sum1=0;
                for (int j=0; j<MA_day4; j++) {
                    if (isUseAdjClose==YES) {
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_adjclose] doubleValue];
                    }
                    else{
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_close] doubleValue];
                    }
                }
                indicator_MA_4=sum1/MA_day4;
                
            }
            else {
                indicator_MA_4=close;
                
                
            }
            
            //5
            if (i>=MA_day5) {
                double sum1;
                
                sum1=0;
                for (int j=0; j<MA_day5; j++) {
                    if (isUseAdjClose==YES) {
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_adjclose] doubleValue];
                    }
                    else{
                        sum1=sum1+[[[fhisDa objectAtIndex:i-j] objectForKey:HIS_basic_close] doubleValue];
                    }
                }
                indicator_MA_5=sum1/MA_day5;
                
            }
            else {
                indicator_MA_5=close;
                
                
            }
        }
        //訊號
        {
            if (i>0) {
                NSMutableDictionary *his_dic_1=[fhisDa objectAtIndex:i-1];  
                
                indicator_MA_1_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MA] objectForKey:DB_his_data_indicator_MA_1] doubleValue];   
                indicator_MA_2_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MA] objectForKey:DB_his_data_indicator_MA_2] doubleValue];                                 
                //買賣訊號
                if (indicator_MA_1>indicator_MA_2 && indicator_MA_1_1<indicator_MA_2_1) {
                    MA_BS=1;
                }
                else if (indicator_MA_1<indicator_MA_2 && indicator_MA_1_1>indicator_MA_2_1) {
                    MA_BS=-1;
                }
                else {
                    MA_BS=0;
                }
                
                //狀態
                if (indicator_MA_1>indicator_MA_2) {
                    MA_State=1;
                }
                else {
                    MA_State=-1;
                }
                
            }
            
        }                        
    }
    
    //存入
    {
                
        //最後
        NSMutableDictionary *dic_indicator_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_signal_key=[[NSMutableDictionary alloc] init];                            
        //指標
        {
             
            
            //CL
            [dic_indicator_key setObject:[NSNumber numberWithDouble:close] forKey:CL_his_data_indicator_serial_sample];   
            [dic_indicator_key setObject:[NSNumber numberWithDouble:indicator_MA_1] forKey:CL_his_data_indicator_MA_1];  
            [dic_indicator_key setObject:[NSNumber numberWithDouble:indicator_MA_2] forKey:CL_his_data_indicator_MA_2]; 
            [dic_indicator_key setObject:[NSNumber numberWithDouble:indicator_MA_3] forKey:CL_his_data_indicator_MA_3];                    
            [dic_indicator_key setObject:[NSNumber numberWithDouble:indicator_MA_4] forKey:CL_his_data_indicator_MA_4];                    
            [dic_indicator_key setObject:[NSNumber numberWithDouble:indicator_MA_5] forKey:CL_his_data_indicator_MA_5]; 
            
            //添加
            [fdic_indicator setObject:dic_indicator_key forKey:calculate_key];
            [dic_indicator_key release];
        } 
        //訊號
        {
            
            
            //CL
            [dic_signal_key setObject:[NSNumber numberWithDouble:MA_BS] forKey:CL_his_data_signal_MA_BS];                     
            [dic_signal_key setObject:[NSNumber numberWithDouble:MA_State] forKey:CL_his_data_signal_MA_State]; 
            
            //添加
            [fdic_signal setObject:dic_signal_key forKey:calculate_key]; 
            [dic_signal_key release];
        }                              
        
        
    }

}

//KD
-(void)calculateFunction_KD:(NSString *)calculate_key fhisDa:(NSMutableArray *)fhisDa index:(int)i fdic_indicator:(NSMutableDictionary *)fdic_indicator fdic_signal:(NSMutableDictionary *)fdic_signal fdic_temp:(NSMutableDictionary *)fdic_temp fdic_profit:(NSMutableDictionary *)fdic_profit{
    
    
    //1.參數
    int N,M1,M2;
    {
        
        
        //取出參數存放位置字典
        NSString *DWM;
        NSMutableDictionary *para_dic_all  ;
        NSMutableDictionary *para_dic_all_method ;//取出特定方法下的參數值
        NSMutableDictionary *para_dic; //取出特定週期的參數值
        
        DWM=day; //!!!!!!! 很重要目前是以日線參數來進行計算
        
        para_dic_all=  [[self data_object_para] Para_calculate_method:calculate_key period:DWM]  ;
        
        para_dic_all_method=[para_dic_all objectForKey:calculate_key ];
        para_dic=[para_dic_all_method objectForKey:day];
        
        
        
        N   =[[para_dic objectForKey:Para_1] intValue];
        M1   =[[para_dic objectForKey:Para_2] intValue];
        M2   =[[para_dic objectForKey:Para_3] intValue];
    }
    
    //2.計算 kd
    float Kvalue;
    float Dvalue;
    float K3D2;
    float RSV;
    if (i>N && i>M1 && i>M2) {
        
        float close;
        close=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_close] doubleValue];
        
        
        float llv,hhv;
        llv=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_low] doubleValue];
        
        for (int bi=0; bi<N; bi++) {
            if (llv>[[[fhisDa objectAtIndex:i-bi] objectForKey:HIS_basic_low] doubleValue]) {
                
                llv=[[[fhisDa objectAtIndex:i-bi] objectForKey:HIS_basic_low] doubleValue];
            }
        }
        
        hhv=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_high] doubleValue];
        for (int bi=0; bi<N; bi++) {
            if (hhv<[[[fhisDa objectAtIndex:i-bi] objectForKey:HIS_basic_high] doubleValue]) {
                hhv=[[[fhisDa objectAtIndex:i-bi] objectForKey:HIS_basic_high] doubleValue];
            }
        }
        
        if (!(hhv==llv)) {
            RSV=(close-llv)/(hhv-llv)*100;
            
            float Kvalue_1=[self get_his_temp_value:HIS_dic_temp_KD_K calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            float Dvalue_1=[self get_his_temp_value:HIS_dic_temp_KD_D calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            Kvalue=RSV/M1+Kvalue_1*(M1-1)/M1;
            Dvalue=Kvalue/M2+Dvalue_1*(M2-1)/M2;
            K3D2=Kvalue*3-Dvalue*2;
            
        }
        else{
            Kvalue=0;
            Dvalue=0;
            K3D2=0;
            
            
        }
        
        
        
        
        
        
    }
    else{
        Kvalue=0;
        Dvalue=0;
        K3D2=0;
        
    }
    
    //5.訊號判斷
    int BuyOrSell;      //此位置 i 是否要買或賣
    int Position_State; //此位置 i 多空狀態
    //int BS_Stop;        //停損機制 2表示做空停損 -2表示做多停損
    
    double  Kvalue_1, Dvalue_1;
    {
        BuyOrSell=0;
        Position_State=0;
       // BS_Stop=0;
        
        
        
        if (i>N && i>M1 && i>M2) {
            
            NSMutableDictionary *his_dic_1=[fhisDa objectAtIndex:i-1];
            
            Kvalue_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_KD] objectForKey:CL_his_data_indicator_KD_K] doubleValue];
            
            Dvalue_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_KD] objectForKey:CL_his_data_indicator_KD_D] doubleValue];
            
            
            
            
            
            
            //買賣訊號
            if (Dvalue > Kvalue && Dvalue_1 < Kvalue_1) {
                BuyOrSell=-1;
                
            }
            else if (Dvalue < Kvalue && Dvalue_1 > Kvalue_1) {
                BuyOrSell=1;
            }
            else {
                BuyOrSell=0;
            }
            
            //狀態
            if (Dvalue > Kvalue) {
                Position_State=-1;
            }
            else {
                Position_State=1;
            }
            
            
        }
        
        
    }
    
    
    //存入
    {
        
        //字典初始化
        NSMutableDictionary *dic_indicator_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_signal_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_temp_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_profit_key=[[NSMutableDictionary alloc] init];
        
        
        //指標
        {
            
            
            //CL
            [dic_indicator_key setObject:[NSNumber numberWithDouble:Kvalue] forKey:CL_his_data_indicator_KD_K];
            [dic_indicator_key setObject:[NSNumber numberWithDouble:Dvalue] forKey:CL_his_data_indicator_KD_D];
            [dic_indicator_key setObject:[NSNumber numberWithDouble:K3D2] forKey:CL_his_data_indicator_KD_3K2D];
            
            
            
            //添加
            [fdic_indicator setObject:dic_indicator_key forKey:calculate_key];
            [dic_indicator_key release];
        }
        
        //訊號
        {
            //CL
            [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_KD_BS];
            [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_KD_State];
            
            //添加
            [fdic_signal setObject:dic_signal_key forKey:calculate_key];
            [dic_signal_key release];
        }
        
        //損益 dic_profit_key （已經實現損益與未實現損益 存放所有的序列 至於其他的損益數據就採用暫存模式存放）
        {
            
            
            
            //添加
            [fdic_profit setObject:dic_profit_key forKey:calculate_key];
            [dic_profit_key release];
        }
        
        //temp dic_temp_key
        {
            
            [dic_temp_key setObject:[NSNumber numberWithDouble:Kvalue] forKey:HIS_dic_temp_KD_K];
            
            [dic_temp_key setObject:[NSNumber numberWithDouble:Dvalue] forKey:HIS_dic_temp_KD_D];
            
            //添加
            [fdic_temp setObject:dic_temp_key forKey:calculate_key];
            [dic_temp_key release];
            
        }
        
    }
    
}


//MACD
-(void)calculateFunction_MACD:(NSString *)calculate_key fhisDa:(NSMutableArray *)fhisDa index:(int)i fdic_indicator:(NSMutableDictionary *)fdic_indicator fdic_signal:(NSMutableDictionary *)fdic_signal fdic_temp:(NSMutableDictionary *)fdic_temp fdic_profit:(NSMutableDictionary *)fdic_profit{
   
    //1.參數
    int MACD_N,EMA1_N,EMA2_N;
    {
        
        //取出參數存放位置字典
        NSString *DWM;
        NSMutableDictionary *para_dic_all  ;
        NSMutableDictionary *para_dic_all_method ;//取出特定方法下的參數值
        NSMutableDictionary *para_dic; //取出特定週期的參數值
        
        DWM=day; //!!!!!!! 很重要目前是以日線參數來進行計算
        
        para_dic_all=  [[self data_object_para] Para_calculate_method:calculate_key period:DWM]  ;
        
        para_dic_all_method=[para_dic_all objectForKey:calculate_key ];
        para_dic=[para_dic_all_method objectForKey:day];
        
        
        
        MACD_N   =[[para_dic objectForKey:Para_1] intValue];
        EMA1_N   =[[para_dic objectForKey:Para_2] intValue];
        EMA2_N   =[[para_dic objectForKey:Para_3] intValue];
    }
    
    //計算 MACD
    float df=0;
    float dif=0;
    
    float ema1=0;
    float ema2=0;
    float macd=0;
    //DI 計算
    float di=0;
    {
        float close,high,low;
        close=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_close] doubleValue];
        high=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_high] doubleValue];
        low=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_low] doubleValue];
        
        di=(high+low+close*2)/4;
        
    }
    
    //EMA DIFF MACD 計算
    if (i>MACD_N && i>EMA1_N && i>EMA2_N) {
        
        //EMA
        //指數平滑公式 若Y=EMA(X，N)，则Y=［2*X+(N-1)*Y’］/(N+1)，其中Y’表示上一周期的Y值
        {
            float ema1_1=[self get_his_temp_value:HIS_dic_temp_MACD_EMA1 calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            float ema2_1=[self get_his_temp_value:HIS_dic_temp_MACD_EMA2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            ema1=(2*di +(EMA1_N-1)*ema1_1)/( EMA1_N+1);
            ema2=(2*di +(EMA2_N-1)*ema2_1)/( EMA2_N+1);
            
            
        }
        
        //DIF
        {
            dif=ema1-ema2;
        }
        
        //MACD
        {
            float macd_1=[self get_his_temp_value:HIS_dic_temp_MACD_MACD calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            macd=(2*dif +(MACD_N-1)*macd_1)/( MACD_N+1);
            
        }
        
        df=dif-macd;
        
    }
    
    //存入
    {
        
        //字典初始化
        NSMutableDictionary *dic_indicator_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_signal_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_temp_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_profit_key=[[NSMutableDictionary alloc] init];
        
        
        //指標
        {
            
            
            //CL
            [dic_indicator_key setObject:[NSNumber numberWithDouble:df] forKey:CL_his_data_indicator_MACD_DF];
            [dic_indicator_key setObject:[NSNumber numberWithDouble:dif] forKey:CL_his_data_indicator_MACD_DIF];
            [dic_indicator_key setObject:[NSNumber numberWithDouble:macd] forKey:CL_his_data_indicator_MACD_MACD];
            
            
            
            //添加
            [fdic_indicator setObject:dic_indicator_key forKey:calculate_key];
            [dic_indicator_key release];
        }
        
        //訊號
        {
            //CL
            
            
            //添加
            [fdic_signal setObject:dic_signal_key forKey:calculate_key];
            [dic_signal_key release];
        }
        
        //損益 dic_profit_key （已經實現損益與未實現損益 存放所有的序列 至於其他的損益數據就採用暫存模式存放）
        {
            
            
            
            //添加
            [fdic_profit setObject:dic_profit_key forKey:calculate_key];
            [dic_profit_key release];
        }
        
        //temp dic_temp_key
        {
            
            [dic_temp_key setObject:[NSNumber numberWithDouble:di] forKey:HIS_dic_temp_MACD_DI];
            
            [dic_temp_key setObject:[NSNumber numberWithDouble:ema1] forKey:HIS_dic_temp_MACD_EMA1];
            
            [dic_temp_key setObject:[NSNumber numberWithDouble:ema2] forKey:HIS_dic_temp_MACD_EMA2];
            
            [dic_temp_key setObject:[NSNumber numberWithDouble:macd] forKey:HIS_dic_temp_MACD_MACD];
            
            //添加
            [fdic_temp setObject:dic_temp_key forKey:calculate_key];
            [dic_temp_key release];
            
        }
        
    }
    
   
    
}

//計算方法函數 LF
-(void)calculateFunction_LF:(NSString *)calculate_key fhisDa:(NSMutableArray *)fhisDa index:(int)i fdic_indicator:(NSMutableDictionary *)fdic_indicator fdic_signal:(NSMutableDictionary *)fdic_signal fdic_temp:(NSMutableDictionary *)fdic_temp fdic_profit:(NSMutableDictionary *)fdic_profit{

    //1.開高收低 基本每筆資料
    double   open,close ;
    
    NSMutableDictionary *his_dic;
    {
        his_dic=[fhisDa objectAtIndex:i];
        
        //調整收盤價比率
        double adj_ratio;
        {
            double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
            double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
            
            
            if (isUseAdjClose==YES) {
                adj_ratio=adj_close/close;
            }
            else{
                adj_ratio=1;
            }
        }
        
        
        
        
        //high=[[his_dic objectForKey:HIS_basic_high] doubleValue] * adj_ratio;
        //low=[[his_dic objectForKey:HIS_basic_low] doubleValue]   * adj_ratio;
        open=[[his_dic objectForKey:HIS_basic_open] doubleValue] * adj_ratio;
        close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
        
        
        
        
    }
     
    //1.參數
    float Bratio,Sratio;
    int long_Nday,short_Nday;
    float long_cost,short_cost; //交易成本
    float Stop_ratio;           //停損率
    int isUse_Stop;             //是否停損
    {
        
        //取出參數存放位置字典
        NSString *DWM;
        NSMutableDictionary *para_dic_all  ;
        NSMutableDictionary *para_dic_all_method ;//取出特定方法下的參數值
        NSMutableDictionary *para_dic; //取出特定週期的參數值
        
        DWM=day; //!!!!!!! 很重要目前是以日線參數來進行計算
        
        para_dic_all=  [[self data_object_para] Para_calculate_method:calculate_key period:DWM]  ;
        
        para_dic_all_method=[para_dic_all objectForKey:calculate_key ];
        para_dic=[para_dic_all_method objectForKey:day];
        
        Bratio   =[[para_dic objectForKey:Para_1] floatValue];
        long_Nday    =[[para_dic objectForKey:Para_2] intValue];
        
        Sratio  =[[para_dic objectForKey:Para_3] floatValue];        
        short_Nday   =[[para_dic objectForKey:Para_4] intValue];
        
        long_cost =[[para_dic objectForKey:Para_Optimize_long_cost ] floatValue];
        short_cost=[[para_dic objectForKey:Para_Optimize_short_cost ] floatValue];
        Stop_ratio=[[para_dic objectForKey:Para_Optimize_Stop_ratio ] floatValue];
        isUse_Stop=[[para_dic objectForKey:Para_Optimize_isUse_Stop ] intValue];
        
        
    }
          
    //2.計算
    float LF_bout;
    float LF_sout;
    int LF_b;
    int LF_s;
    int LF_b_1;
    int LF_s_1;
    
    //計算
    {
        
        if (i>long_Nday && i>short_Nday) {
        
            if (i>=1) {
                 LF_bout= [self get_his_temp_value:HIS_dic_temp_LF_bout calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                 LF_sout= [self get_his_temp_value:HIS_dic_temp_LF_sout calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LF_b=(int) [self get_his_temp_value:HIS_dic_temp_LF_b calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LF_s=(int) [self get_his_temp_value:HIS_dic_temp_LF_s calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                //紀錄上一期
                LF_b_1=(int) [self get_his_temp_value:HIS_dic_temp_LF_b calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LF_s_1=(int) [self get_his_temp_value:HIS_dic_temp_LF_s calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
            
            
            }
            else{
                 LF_bout=0;
                 LF_sout=0;
                 LF_b=0;
                 LF_s=0;
                 LF_b_1=0;
                 LF_s_1=0;
                
            
            }
            
            
            int start_i;
            {
                if (long_Nday>short_Nday) {
                    start_i=long_Nday;
                }
                else{
                    start_i=short_Nday;                    
                }
            
                
            }
            
            //做多區間
            float BRange;
            {
                float rhigh=0;
                float rlow=0;
                {
                    //區間最大值
                    for (int Hi=0;Hi<long_Nday ; Hi++) {
                        
                        if (Hi==0) {
                            
                            rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                        }
                        else{
                            if (rhigh<[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                
                                rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                
                            }
                            
                            
                        }
                        
                    }
                    
                    //區間最小值
                    for (int Li=0;Li<long_Nday ; Li++) {
                        
                        if (Li==0) {
                            
                            rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                        }
                        else{
                            
                            if (rlow>[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                
                                rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                
                            }
                            
                            
                        }
                        
                    }
                    
                
                
                }
                BRange=rhigh-rlow;
            }
            
            //做空區間
            float SRange;
            {
                float rhigh=0;
                float rlow=0;
                {
                    //區間最大值
                    for (int Hi=0;Hi<short_Nday ; Hi++) {
                        
                        if (Hi==0) {
                            
                            rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                        }
                        else{
                            if (rhigh<[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                
                                rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                
                            }
                            
                            
                        }
                        
                    }
                    
                    //區間最小值
                    for (int Li=0;Li<short_Nday ; Li++) {
                        
                        if (Li==0) {
                            
                            rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                        }
                        else{
                            
                            if (rlow>[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                
                                rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                
                            }
                            
                            
                        }
                        
                    }
                    
                    
                }
              
                SRange=rhigh-rlow;
            }
            
            {
               
                float close=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_adjclose] doubleValue];
               
                
                
                if (LF_b==0 && LF_s==0 && i==start_i ) {
                    LF_b=1;
                    LF_s=0;
                    LF_bout=close-BRange*Bratio;
                    LF_sout=0;
                }
                if (LF_b==1 & LF_bout+BRange<close) {
                    LF_bout=LF_bout+BRange*Bratio;
                }
                if (LF_b==1 && close<LF_bout) {
                    LF_b=0;
                    LF_s=1;
                    LF_sout=close+SRange*Sratio;
                    LF_bout=0;
                }
                
                /*
                if (LF_b==0 && LF_s==0 && close<average1 & close_1>average1_1 ) {
                    LF_s=1;
                    LF_b=0;
                    LF_sout=close+SRange*Sratio;
                    LF_bout=0;
                    
                }
                
                 */
                
                if (LF_s==1 & LF_sout-SRange>close) {
                    LF_sout=LF_sout-SRange*Sratio;
                }	
                if (LF_s==1 && close>LF_sout) {
                    LF_s=0;
                    LF_b=1;
                    LF_bout=close-BRange*Bratio;
                    LF_sout=0;
                }
                
            
            
            }
            
            
        
        }
        else{
            
            LF_b=1;
            LF_s=0;
            LF_bout=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_high] doubleValue]*(1-Bratio);
            LF_sout=0;
            
            
        }
            
    }
    
    //5.訊號判斷
    int BuyOrSell;      //此位置 i 是否要買或賣
    int Position_State; //此位置 i 多空狀態
    int BS_Stop; //停損機制 2表示做空停損 -2表示做多停損
    {
        BuyOrSell=0;
        Position_State=0;
        BS_Stop=0;
         
        if (i>0) {
            
            //買賣訊號
            if (LF_b_1==1 && LF_s==1) {
                BuyOrSell=-1;
                
            }
            else if (LF_s_1==1 && LF_b==1) {
                BuyOrSell=1;
            }
            else {
                BuyOrSell=0;
            }
            
            //狀態
            if (LF_s==1) {
                Position_State=-1;
            }
            else {
                Position_State=1;
            }
            
            
        }
        
        
    }
    
    //6.損益部位
    double last_trade_long_profitratio;         //最後一筆做多獲利率
    double last_trade_short_profitratio;        //最後一筆做空獲利率
    double realized_trade_long_profitratio;     //已經實現做多損益
    double realized_trade_short_profitratio;    //已經實現做空損益
    double realized_trade_long_profitratio_sum; //已經實現做多損益合計
    double realized_trade_short_profitratio_sum;//已經實現做空損益合計
    
    
    
    double long_total_count; //做多交易次數
    double long_win_count;   //做多交易賺錢次數
    double long_win_ratio;   //做多勝率
    
    double short_total_count; //做空交易次數
    double short_win_count;   //做空交易賺錢次數
    double short_win_ratio;   //做空勝率
    
    double ls_total_count; //多空交易次數
    double ls_win_count;   //多空交易賺錢次數
    double ls_win_ratio;   //多空勝率
    
    double long_max_gain; //做多最大獲利率
    double long_max_loss; //做多最大虧損率
    double short_max_gain; //做空最大獲利率
    double short_max_loss; //做空最大虧損率
    double ls_max_gain;  //多空最大獲利率
    double ls_max_loss; //多空最大虧損率
    
    double year; //開始計算日期
    
    double return_long;// 作多年化報酬率
    double return_short;// 作空年化報酬率
    double return_ls;// 作空年化報酬率
    
    int BS_last ;// 最後一期買賣方向 因為是以隔天開盤價作為當期買賣價位
    double enter_price;         //最後一期買進場價位
    double enter_price_average; //平均買進場價位
    
    {
        //變數歸0
        {
            last_trade_long_profitratio=0;
            last_trade_short_profitratio=0;
            
            realized_trade_long_profitratio=0;
            realized_trade_short_profitratio=0;
            
            realized_trade_long_profitratio_sum=0;
            realized_trade_short_profitratio_sum=0;
            
            long_total_count=0;
            long_win_count=0;
            long_win_ratio=0;
            
            short_total_count=0;
            short_win_count=0;
            short_win_ratio=0;
            
            ls_total_count=0;
            ls_win_count=0;
            ls_win_ratio=0;
            
            long_max_gain=0; //做多最大獲利率
            long_max_loss=0; //做多最大虧損率
            short_max_gain=0; //做空最大獲利率
            short_max_loss=0; //做空最大虧損率
            ls_max_gain=0;  //多空最大獲利率
            ls_max_loss=0; //多空最大虧損率
            
            
            BS_last=0;
            enter_price=0;
            enter_price_average=0;
            
            year=0;
            
            return_long=0;
            return_short=0;
            return_ls=0;
        }
        
        
        if (i>0) {
            
            
            int BS_1 ;// 前一期買賣動作方向 因為是以隔天開盤價作為當期買賣價位
            BS_1=0;
            
            //停損機制
            int BS_Stop_1; //前一期是否有出現停損動作
            BS_Stop_1=0;
            
            //1.取出前一期的資料
            NSMutableDictionary *his_dic_1=[fhisDa objectAtIndex:i-1];//前一筆
            NSMutableDictionary *his_dic_0=[fhisDa objectAtIndex:0];  //第0筆
            
            if ([calculate_key isEqualToString:Defaults_Calculate_LF1]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_signal_LF1_BS_Stop] intValue];
                
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_signal_LF1_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_short_win_ratio_temp] doubleValue];
                
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_LS_win_ratio_temp] doubleValue];
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF1] objectForKey:CL_his_data_profit_LF1_LS_max_loss_temp] doubleValue];
                
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LF2]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_signal_LF2_BS_Stop] intValue];
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_signal_LF2_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_short_win_ratio_temp] doubleValue];
                
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_LS_win_ratio_temp] doubleValue];
                
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF2] objectForKey:CL_his_data_profit_LF2_LS_max_loss_temp] doubleValue];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LF3]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_signal_LF3_BS_Stop] intValue];
                
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_signal_LF3_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_short_win_ratio_temp] doubleValue];
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_LS_win_ratio_temp] doubleValue];
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LF3] objectForKey:CL_his_data_profit_LF3_LS_max_loss_temp] doubleValue];
                
                
            }
            
            
            //2.判斷上一期是否有買賣動作
            if (BS_1==0) {
                enter_price=[self get_his_temp_value:HIS_dic_temp_profit_enterprice calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                enter_price_average=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                
                //停損機制
                //前一期是否需要停損
                if (BS_Stop_1==-2) {
                    //前一期出現需要做多停損訊號
                    BS_last=0;
                    //作多出場損益
                    {
                        //做多最近一筆 含有交易成本
                        realized_trade_long_profitratio=(open-enter_price)/enter_price*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                        
                        //累計做多交易次數
                        long_total_count=long_total_count+1;
                        
                        //做多交易賺錢次數
                        if (realized_trade_long_profitratio>0) {
                            //賺錢才可以+1
                            long_win_count=long_win_count+1;
                        }
                        else{
                            long_win_count=long_win_count;
                        }
                        
                        //勝率
                        if (long_total_count>0) {
                            long_win_ratio= long_win_count/long_total_count*100;
                        }
                        else{
                            long_win_ratio=0;
                        }
                        
                        //做多最大獲利
                        if (realized_trade_long_profitratio>long_max_gain) {
                            long_max_gain=realized_trade_long_profitratio;
                        }
                        
                        //做多最大損失
                        if (realized_trade_long_profitratio<long_max_loss) {
                            long_max_loss=realized_trade_long_profitratio;
                        }
                        
                        
                    }
                    
                }
                else if (BS_Stop_1==2){
                    //前一期出現做空需要停損的訊號
                    BS_last=0;
                    //作空出場損益
                    {
                        //做空最近一筆 含有交易成本
                        realized_trade_short_profitratio=(enter_price-open)/enter_price*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                        
                        
                        //累計做空交易次數
                        short_total_count=short_total_count+1;
                        
                        
                        //做空交易賺錢次數
                        if (realized_trade_short_profitratio>0) {
                            //賺錢才可以+1
                            short_win_count=short_win_count+1;
                        }
                        else{
                            short_win_count=short_win_count;
                        }
                        
                        //勝率
                        if (short_total_count>0) {
                            short_win_ratio= short_win_count/short_total_count*100;
                        }
                        else{
                            short_win_ratio=0;
                        }
                        
                        
                        //做空最大獲利
                        if (realized_trade_short_profitratio>short_max_gain) {
                            short_max_gain=realized_trade_short_profitratio;
                        }
                        
                        //做空最大損失
                        if (realized_trade_short_profitratio<short_max_loss) {
                            short_max_loss=realized_trade_short_profitratio;
                        }
                    }
                    
                }
                else{
                    //表示上一期無買賣動作
                    //取出最後一筆的狀態 在轉移到下一期
                    BS_last= [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                }
                
                
            }
            else{
                //表示上一期有買賣動作
                
                //1.計算已經實現損益
                {
                    //上一期尚未動作之前的部位
                    int BS_last_unchange;        //上一期的部位方向
                    double enterprice_last_unchange;//上一期的部位的進場價格還尚未更新到本期的開盤價之前的資料
                    
                    BS_last_unchange=[self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    enterprice_last_unchange=[self get_his_temp_value:HIS_dic_temp_profit_enterprice calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                    //計算已經實現損益與累計實現損益
                    if (BS_last_unchange==1) {
                        
                        //做多最近一筆 含有交易成本
                        realized_trade_long_profitratio=(open-enterprice_last_unchange)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                        
                        //累計做多交易次數
                        long_total_count=long_total_count+1;
                        
                        //做多交易賺錢次數
                        if (realized_trade_long_profitratio>0) {
                            //賺錢才可以+1
                            long_win_count=long_win_count+1;
                        }
                        else{
                            long_win_count=long_win_count;
                        }
                        
                        //勝率
                        if (long_total_count>0) {
                            long_win_ratio= long_win_count/long_total_count*100;
                        }
                        else{
                            long_win_ratio=0;
                        }
                        
                        //做多最大獲利
                        if (realized_trade_long_profitratio>long_max_gain) {
                            long_max_gain=realized_trade_long_profitratio;
                        }
                        
                        //做多最大損失
                        if (realized_trade_long_profitratio<long_max_loss) {
                            long_max_loss=realized_trade_long_profitratio;
                        }
                        
                        
                    }
                    else if (BS_last_unchange==-1){
                        //做空最近一筆 含有交易成本
                        realized_trade_short_profitratio=(enterprice_last_unchange-open)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                        
                        
                        //累計做空交易次數
                        short_total_count=short_total_count+1;
                        
                        
                        //做空交易賺錢次數
                        if (realized_trade_short_profitratio>0) {
                            //賺錢才可以+1
                            short_win_count=short_win_count+1;
                        }
                        else{
                            short_win_count=short_win_count;
                        }
                        
                        //勝率
                        if (short_total_count>0) {
                            short_win_ratio= short_win_count/short_total_count*100;
                        }
                        else{
                            short_win_ratio=0;
                        }
                        
                        
                        //做空最大獲利
                        if (realized_trade_short_profitratio>short_max_gain) {
                            short_max_gain=realized_trade_short_profitratio;
                        }
                        
                        //做空最大損失
                        if (realized_trade_short_profitratio<short_max_loss) {
                            short_max_loss=realized_trade_short_profitratio;
                        }
                        
                        
                        
                    }
                    
                    //多空合計
                    ls_total_count=long_total_count+short_total_count;
                    ls_win_count=long_win_count+short_win_count;
                    
                    if (ls_total_count>0) {
                        ls_win_ratio=ls_win_count/ls_total_count*100;
                    }
                    else{
                        ls_win_ratio=0;
                    }
                    
                    //多空最大獲利
                    if (realized_trade_long_profitratio>ls_max_gain) {
                        ls_max_gain=realized_trade_long_profitratio;
                    }
                    if (realized_trade_short_profitratio>ls_max_gain) {
                        ls_max_gain=realized_trade_short_profitratio;
                    }
                    //多空最大損失
                    if (realized_trade_long_profitratio<ls_max_loss) {
                        ls_max_loss=realized_trade_long_profitratio;
                    }
                    if (realized_trade_short_profitratio<ls_max_loss) {
                        ls_max_loss=realized_trade_short_profitratio;
                    }
                }
                
                //2.更新最新資料
                BS_last=BS_1;
                enter_price=open;
            }
            
            //有買賣動作之後，本期計算出未實現損益
            if (BS_last  ==1 && enter_price>0) {
                //做多未實現損益
                last_trade_long_profitratio =(close-enter_price)/enter_price*100 ;
            }
            else if(BS_last  == -1 && enter_price>0){
                //做空未實現損益
                last_trade_short_profitratio =(enter_price-close)/enter_price*100 ;
                
            }
            else{
                last_trade_long_profitratio=0;
                last_trade_short_profitratio=0;
                
            }
            
            
            
            //停損機制
            //判斷是否需要停損
            if (isUse_Stop==1) {
                
                
                if (Stop_ratio*-100>last_trade_long_profitratio) {
                    //做多未實現損益超過停損率 下期停損掉
                    BS_Stop=-2;
                }
                else if (Stop_ratio*-100>last_trade_short_profitratio){
                    //做空未實現損益超過停損率 下期停損掉
                    BS_Stop=2;
                    
                }
                
                
            }
            
            
            
            
            
            
            //3.年限
            NSDate *date_0;
            date_0=[his_dic_0 objectForKey:HIS_basic_date];
            
            NSDate  *date_now;
            date_now=[his_dic objectForKey:HIS_basic_date];
            
            double l;
            
            l=[date_now timeIntervalSinceDate:date_0]/86400;
            
            year=l/365;
            
            
            //4.報酬率
            {
                //作多年化報酬率
                return_long=realized_trade_long_profitratio_sum/year;
                
                //作空年化報酬率
                return_short=realized_trade_short_profitratio_sum/year;
                
                //多空年化報酬率
                return_ls=(realized_trade_long_profitratio_sum+realized_trade_short_profitratio_sum)/year;
                
            }
            
        }
        
    }
    
    //7.存入記憶體
    {
        
        //字典初始化
        NSMutableDictionary *dic_indicator_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_signal_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_temp_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_profit_key=[[NSMutableDictionary alloc] init];
        
        
        //指標
        {
            if ([calculate_key isEqualToString:Defaults_Calculate_LF1]){
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LF_bout] forKey:CL_his_data_indicator_LF1_Long_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LF_sout] forKey:CL_his_data_indicator_LF1_Short_StopPrice];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LF2]){
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LF_bout] forKey:CL_his_data_indicator_LF2_Long_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LF_sout] forKey:CL_his_data_indicator_LF2_Short_StopPrice];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LF3]){
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LF_bout] forKey:CL_his_data_indicator_LF3_Long_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LF_sout] forKey:CL_his_data_indicator_LF3_Short_StopPrice];
            }
            
            
            
            
            //添加
            [fdic_indicator setObject:dic_indicator_key forKey:calculate_key];
            [dic_indicator_key release];
        }
        
        //訊號 dic_signal_key
        {
            
            if ([calculate_key isEqualToString:Defaults_Calculate_LF1]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LF1_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LF1_State];
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_LF1_BS_Stop];
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LF2]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LF2_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LF2_State];
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_LF2_BS_Stop];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LF3]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LF3_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LF3_State];
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_LF3_BS_Stop];
            }
            
            
            //添加
            [fdic_signal setObject:dic_signal_key forKey:calculate_key];
            [dic_signal_key release];
        }
        
        //損益 dic_profit_key （已經實現損益與未實現損益 存放所有的序列 至於其他的損益數據就採用暫存模式存放）
        {
            //最後一筆買賣尚未實現損益報酬率
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_LF1]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF1_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF1_shortratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_LF1_longshortratio_lasttrade];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LF2]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF2_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF2_shortratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_LF2_longshortratio_lasttrade];
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LF3]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF3_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF3_shortratio_lasttrade];
                    
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_LF3_longshortratio_lasttrade];
                }
            }
            //已經實現損益報酬率合計
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_LF1]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF1_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF1_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF1_longshortratio_realizedtrade];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LF2]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF2_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF2_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF2_longshortratio_realizedtrade];
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LF3]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF3_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF3_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF3_longshortratio_realizedtrade];
                    
                }
            }
            
            //添加
            [fdic_profit setObject:dic_profit_key forKey:calculate_key];
            [dic_profit_key release];
        }
        
        //temp dic_temp_key
        {
          
            //指標運算所需要使用
            {
                [dic_temp_key setObject:[NSNumber numberWithDouble:LF_bout] forKey:HIS_dic_temp_LF_bout];
                
                [dic_temp_key setObject:[NSNumber numberWithDouble:LF_sout] forKey:HIS_dic_temp_LF_sout];
                
                [dic_temp_key setObject:[NSNumber numberWithInt:LF_b] forKey:HIS_dic_temp_LF_b];
                
                [dic_temp_key setObject:[NSNumber numberWithInt:LF_s] forKey:HIS_dic_temp_LF_s];
            }
            
            //損益分析計算需要
            {
                //最後一筆買賣方向
                [dic_temp_key setObject:[NSNumber numberWithInt:BS_last] forKey:HIS_dic_temp_profit_bs];
                
                //最後一筆進場價位
                [dic_temp_key setObject:[NSNumber numberWithDouble:enter_price] forKey:HIS_dic_temp_profit_enterprice];
                
                //平均進場價位
                [dic_temp_key setObject:[NSNumber numberWithDouble:enter_price_average] forKey:HIS_dic_temp_profit_enterprice_average];
                
                
            }
            
            //損益分析結果最後一筆輸出
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_LF1]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF1_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF1_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF1_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF1_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF1_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF1_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF1_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF1_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF1_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF1_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF1_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF1_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF1_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF1_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF1_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF1_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF1_LS_max_loss_temp];
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF1_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF1_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF1_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF1_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF1_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF1_LS_return_temp];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LF2]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF2_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF2_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF2_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF2_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF2_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF2_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF2_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF2_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF2_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF2_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF2_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF2_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF2_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF2_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF2_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF2_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF2_LS_max_loss_temp];
                    
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF2_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF2_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF2_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF2_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF2_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF2_LS_return_temp];
                    
                    
                }
                else   if ([calculate_key isEqualToString:Defaults_Calculate_LF3]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF3_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF3_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF3_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF3_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF3_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF3_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF3_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF3_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF3_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF3_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF3_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF3_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF3_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF3_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF3_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF3_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF3_LS_max_loss_temp];
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF3_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF3_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF3_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF3_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF3_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF3_LS_return_temp];
                    
                }
                
                
            }
            
            //添加
            [fdic_temp setObject:dic_temp_key forKey:calculate_key];
            [dic_temp_key release];
            
        }
        
    }
    

}


//MESA
-(void)calculateFunction_MESA:(NSString *)calculate_key
                       fhisDa:(NSMutableArray *)fhisDa
                        index:(int)i
               fdic_indicator:(NSMutableDictionary *)fdic_indicator
                  fdic_signal:(NSMutableDictionary *)fdic_signal
                    fdic_temp:(NSMutableDictionary *)fdic_temp
                  fdic_profit:(NSMutableDictionary *)fdic_profit{
    
    
    
    //1.開高收低 基本每筆資料
    double  high,low,open,close ;
    
    NSMutableDictionary *his_dic;
    {
        his_dic=[fhisDa objectAtIndex:i];
        
        //調整收盤價比率
        double adj_ratio;
        {
            double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
            double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
            
            
            if (isUseAdjClose==YES) {
                adj_ratio=adj_close/close;
            }
            else{
                adj_ratio=1;
            }
        }
        
        
        
        
        high=[[his_dic objectForKey:HIS_basic_high] doubleValue] * adj_ratio;
        low=[[his_dic objectForKey:HIS_basic_low] doubleValue]   * adj_ratio;
        open=[[his_dic objectForKey:HIS_basic_open] doubleValue] * adj_ratio;
        close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
        
        
        
        
    }
    
    
    //2.計算用的變數
    double Smooth,price,Detrender,Period,Q1,l1,jl,jQ,l2,Q2,Re,lm,SmoothPeriod,Phase,DeltaPhase,alpha,MAMA,FAMA;
    {
        
        Phase=0;
        
    }
    
    //3.參數
    float FastLim,SlowLim;      //技術指標
    float long_cost,short_cost; //交易成本
    float Stop_ratio;           //停損率
    int isUse_Stop;             //是否停損
    {
        //取出參數存放位置字典
        NSString *DWM;
        NSMutableDictionary *para_dic_all  ;
        NSMutableDictionary *para_dic_all_method ;//取出特定方法下的參數值
        NSMutableDictionary *para_dic; //取出特定週期的參數值
        
        DWM=day; //!!!!!!! 很重要目前是以日線參數來進行計算
        
        para_dic_all=  [[self data_object_para] Para_calculate_method:calculate_key period:DWM]  ;
        
        para_dic_all_method=[para_dic_all objectForKey:calculate_key ];
        para_dic=[para_dic_all_method objectForKey:day];
        
        //取出參數值
        SlowLim   =[[para_dic objectForKey:Para_1] floatValue];
        FastLim   =[[para_dic objectForKey:Para_2 ] floatValue];
        long_cost =[[para_dic objectForKey:Para_Optimize_long_cost ] floatValue];
        short_cost=[[para_dic objectForKey:Para_Optimize_short_cost ] floatValue];
        Stop_ratio=[[para_dic objectForKey:Para_Optimize_Stop_ratio ] floatValue];
        isUse_Stop=[[para_dic objectForKey:Para_Optimize_isUse_Stop ] intValue];
        
        
    }
    
    //4.計算MESA
    {
        price =(high +low)/2;
        
        
        Smooth =(4 * price + 3 *[self get_his_temp_value:HIS_dic_temp_price calculate_key:calculate_key i:i-1 historyData:fhisDa]  + 2 * [self get_his_temp_value:HIS_dic_temp_price calculate_key:calculate_key i:i-2 historyData:fhisDa] + [self get_his_temp_value:HIS_dic_temp_price calculate_key:calculate_key i:i-3 historyData:fhisDa])/10;
        
        Detrender=(0.0962*Smooth+0.5769*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-2 historyData:fhisDa] -0.5769*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-4 historyData:fhisDa]-0.0962*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54);
        
        Q1 =(0.0962*Detrender +0.5769*[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-2 historyData:fhisDa]-0.5769*[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-4 historyData:fhisDa]-0.0962*[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54);
        
        l1 =[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-3 historyData:fhisDa];
        jl=(0.0962*l1+0.5769*[self get_his_temp_value:HIS_dic_temp_l1 calculate_key:calculate_key i:i-2 historyData:fhisDa]-0.5769*[self get_his_temp_value:HIS_dic_temp_l1 calculate_key:calculate_key i:i-4 historyData:fhisDa]-.0962*[self get_his_temp_value:HIS_dic_temp_l1 calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54);
        
        jQ=(0.0962*Q1+.5769*[self get_his_temp_value:HIS_dic_temp_Q1 calculate_key:calculate_key i:i-2 historyData:fhisDa]-.5769*[self get_his_temp_value:HIS_dic_temp_Q1 calculate_key:calculate_key i:i-4 historyData:fhisDa]-0.0962*[self get_his_temp_value:HIS_dic_temp_Q1 calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54) ;
        
        l2=l1-jQ;
        Q2=Q1+jl;
        
        l2=0.2*l2 +0.8*[self get_his_temp_value:HIS_dic_temp_l2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
        Q2=0.2*Q2+0.8*[self get_his_temp_value:HIS_dic_temp_Q2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        Re =l2 *[self get_his_temp_value:HIS_dic_temp_l2 calculate_key:calculate_key i:i-1 historyData:fhisDa]+Q2*[self get_his_temp_value:HIS_dic_temp_Q2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
        lm=l2*[self get_his_temp_value:HIS_dic_temp_Q2 calculate_key:calculate_key i:i-1 historyData:fhisDa]-Q2*[self get_his_temp_value:HIS_dic_temp_l2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        Re =0.2*Re +0.8*[self get_his_temp_value:HIS_dic_temp_Re calculate_key:calculate_key i:i-1 historyData:fhisDa];
        lm=0.2*lm+0.8*[self get_his_temp_value:HIS_dic_temp_lm calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        
        if( lm  !=0 && Re !=0 )
        {
            Period = 360/(atan((lm /Re ))*180/(4*atan(1)));
            
        }
        else {
            Period=0;
        }
        if( Period >1.5*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa])
            Period =1.5*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        if(Period <0.67*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa])
            Period =0.67*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        
        if(Period <6)
            Period =6;
        if(Period >50)
            Period =50;
        
        Period =0.2*Period +0.8*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        
        SmoothPeriod =0.33*Period +0.67*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-1 historyData:fhisDa];
        
        if( l1  !=0 )
            Phase =atan(Q1 /l1 )*180/(4*atan(1));
        
        DeltaPhase=[self get_his_temp_value:HIS_dic_temp_Phase calculate_key:calculate_key i:i-1 historyData:fhisDa]-Phase ;
        
        if(DeltaPhase <1)
            DeltaPhase =1;
        alpha =FastLim/DeltaPhase ;
        
        if(alpha <SlowLim)
            alpha  =SlowLim;
        
        if( alpha >FastLim)
            alpha =FastLim;
        
        MAMA =alpha *price +(1-alpha )*[self get_his_temp_value:HIS_dic_temp_MAMA calculate_key:calculate_key i:i-1 historyData:fhisDa];
        FAMA =0.5*alpha*MAMA+(1-0.5*alpha)*[self get_his_temp_value:HIS_dic_temp_FAMA calculate_key:calculate_key i:i-1 historyData:fhisDa];
    }
    
    //5.訊號判斷
    int BuyOrSell;      //此位置 i 是否要買或賣
    int Position_State; //此位置 i 多空狀態
    int BS_Stop; //停損機制 2表示做空停損 -2表示做多停損
    
    double  FAMA_1, MAMA_1;
    {
        BuyOrSell=0;
        Position_State=0;
        BS_Stop=0;
        
        
        FAMA_1=0;
        MAMA_1=0;
        if (i>0) {
            NSMutableDictionary *his_dic_1=[fhisDa objectAtIndex:i-1];
            
            if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                
                FAMA_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_indicator_MESA1_FAMA] doubleValue];
                
                MAMA_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_indicator_MESA1_MAMA] doubleValue];
                
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                
                FAMA_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_indicator_MESA2_FAMA] doubleValue];
                
                MAMA_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_indicator_MESA2_MAMA] doubleValue];
                
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                FAMA_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_indicator_MESA3_FAMA] doubleValue];
                
                MAMA_1=[[[[his_dic_1 objectForKey:HIS_dic_indicator] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_indicator_MESA3_MAMA] doubleValue];
                
                
            }
            
            
            //買賣訊號
            if (FAMA>MAMA && FAMA_1<MAMA_1) {
                BuyOrSell=-1;
                
            }
            else if (FAMA<MAMA && FAMA_1>MAMA_1) {
                BuyOrSell=1;
            }
            else {
                BuyOrSell=0;
            }
            
            //狀態
            if (FAMA>MAMA) {
                Position_State=-1;
            }
            else {
                Position_State=1;
            }
            
            
        }
        
        
    }
    
    //6.損益部位
    double last_trade_long_profitratio;         //最後一筆做多獲利率
    double last_trade_short_profitratio;        //最後一筆做空獲利率
    double realized_trade_long_profitratio;     //已經實現做多損益
    double realized_trade_short_profitratio;    //已經實現做空損益
    double realized_trade_long_profitratio_sum; //已經實現做多損益合計
    double realized_trade_short_profitratio_sum;//已經實現做空損益合計
    
    double long_total_count; //做多交易次數
    double long_win_count;   //做多交易賺錢次數
    double long_win_ratio;   //做多勝率
    
    double short_total_count; //做空交易次數
    double short_win_count;   //做空交易賺錢次數
    double short_win_ratio;   //做空勝率
    
    double ls_total_count; //多空交易次數
    double ls_win_count;   //多空交易賺錢次數
    double ls_win_ratio;   //多空勝率
    
    double long_max_gain; //做多最大獲利率
    double long_max_loss; //做多最大虧損率
    double short_max_gain; //做空最大獲利率
    double short_max_loss; //做空最大虧損率
    double ls_max_gain;  //多空最大獲利率
    double ls_max_loss; //多空最大虧損率
    
    double year; //開始計算日期
    
    double return_long;// 作多年化報酬率
    double return_short;// 作空年化報酬率
    double return_ls;// 作空年化報酬率
    
    int BS_last ;// 最後一期買賣方向 因為是以隔天開盤價作為當期買賣價位
    double enter_price; //最後一期買進場價位
    {
        //變數歸0
        {
            last_trade_long_profitratio=0;
            last_trade_short_profitratio=0;
            
            realized_trade_long_profitratio=0;
            realized_trade_short_profitratio=0;
            
            realized_trade_long_profitratio_sum=0;
            realized_trade_short_profitratio_sum=0;
            
            long_total_count=0;
            long_win_count=0;
            long_win_ratio=0;
            
            short_total_count=0;
            short_win_count=0;
            short_win_ratio=0;
            
            ls_total_count=0;
            ls_win_count=0;
            ls_win_ratio=0;
            
            long_max_gain=0; //做多最大獲利率
            long_max_loss=0; //做多最大虧損率
            short_max_gain=0; //做空最大獲利率
            short_max_loss=0; //做空最大虧損率
            ls_max_gain=0;  //多空最大獲利率
            ls_max_loss=0; //多空最大虧損率
            
            
            BS_last=0;
            enter_price=0;
            year=0;
            
            return_long=0;
            return_short=0;
            return_ls=0;
        }
        
        
        if (i>0) {
            
            
            int BS_1 ;// 前一期買賣動作方向 因為是以隔天開盤價作為當期買賣價位
            BS_1=0;
            
            //停損機制
            int BS_Stop_1; //前一期是否有出現停損動作
            BS_Stop_1=0;
            
            //1.取出前一期的資料
            NSMutableDictionary *his_dic_1=[fhisDa objectAtIndex:i-1];//前一筆
            NSMutableDictionary *his_dic_0=[fhisDa objectAtIndex:0];  //第0筆
            
            if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_signal_MESA1_BS_Stop] intValue];
                
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_signal_MESA1_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_short_win_ratio_temp] doubleValue];
                
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_LS_win_ratio_temp] doubleValue];
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA1] objectForKey:CL_his_data_profit_MESA1_LS_max_loss_temp] doubleValue];
                
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_signal_MESA2_BS_Stop] intValue];
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_signal_MESA2_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_short_win_ratio_temp] doubleValue];
                
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_LS_win_ratio_temp] doubleValue];
                
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA2] objectForKey:CL_his_data_profit_MESA2_LS_max_loss_temp] doubleValue];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_signal_MESA3_BS_Stop] intValue];
                
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_signal_MESA3_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_short_win_ratio_temp] doubleValue];
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_LS_win_ratio_temp] doubleValue];
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_MESA3] objectForKey:CL_his_data_profit_MESA3_LS_max_loss_temp] doubleValue];
                
                
            }
            
            
            //2.判斷上一期是否有買賣動作
            if (BS_1==0) {
                enter_price=[self get_his_temp_value:HIS_dic_temp_profit_enterprice calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                
                //停損機制
                //前一期是否需要停損
                if (BS_Stop_1==-2) {
                    //前一期出現需要做多停損訊號
                    BS_last=0;
                    //作多出場損益
                    {
                        //做多最近一筆 含有交易成本
                        realized_trade_long_profitratio=(open-enter_price)/enter_price*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                        
                        //累計做多交易次數
                        long_total_count=long_total_count+1;
                        
                        //做多交易賺錢次數
                        if (realized_trade_long_profitratio>0) {
                            //賺錢才可以+1
                            long_win_count=long_win_count+1;
                        }
                        else{
                            long_win_count=long_win_count;
                        }
                        
                        //勝率
                        if (long_total_count>0) {
                            long_win_ratio= long_win_count/long_total_count*100;
                        }
                        else{
                            long_win_ratio=0;
                        }
                        
                        //做多最大獲利
                        if (realized_trade_long_profitratio>long_max_gain) {
                            long_max_gain=realized_trade_long_profitratio;
                        }
                        
                        //做多最大損失
                        if (realized_trade_long_profitratio<long_max_loss) {
                            long_max_loss=realized_trade_long_profitratio;
                        }
                        
                        
                    }
                    
                }
                else if (BS_Stop_1==2){
                    //前一期出現做空需要停損的訊號
                    BS_last=0;
                    //作空出場損益
                    {
                        //做空最近一筆 含有交易成本
                        realized_trade_short_profitratio=(enter_price-open)/enter_price*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                        
                        
                        //累計做空交易次數
                        short_total_count=short_total_count+1;
                        
                        
                        //做空交易賺錢次數
                        if (realized_trade_short_profitratio>0) {
                            //賺錢才可以+1
                            short_win_count=short_win_count+1;
                        }
                        else{
                            short_win_count=short_win_count;
                        }
                        
                        //勝率
                        if (short_total_count>0) {
                            short_win_ratio= short_win_count/short_total_count*100;
                        }
                        else{
                            short_win_ratio=0;
                        }
                        
                        
                        //做空最大獲利
                        if (realized_trade_short_profitratio>short_max_gain) {
                            short_max_gain=realized_trade_short_profitratio;
                        }
                        
                        //做空最大損失
                        if (realized_trade_short_profitratio<short_max_loss) {
                            short_max_loss=realized_trade_short_profitratio;
                        }
                    }
                    
                }
                else{
                    //表示上一期無買賣動作
                    //取出最後一筆的狀態 在轉移到下一期
                    BS_last= [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                }
                
                
            }
            else{
                //表示上一期有買賣動作
                
                //1.計算已經實現損益
                {
                    //上一期尚未動作之前的部位
                    int BS_last_unchange;        //上一期的部位方向
                    double enterprice_last_unchange;//上一期的部位的進場價格還尚未更新到本期的開盤價之前的資料
                    
                    BS_last_unchange=[self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    enterprice_last_unchange=[self get_his_temp_value:HIS_dic_temp_profit_enterprice calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                    //計算已經實現損益與累計實現損益
                    if (BS_last_unchange==1) {
                        
                        //做多最近一筆 含有交易成本
                        realized_trade_long_profitratio=(open-enterprice_last_unchange)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                        
                        //累計做多交易次數
                        long_total_count=long_total_count+1;
                        
                        //做多交易賺錢次數
                        if (realized_trade_long_profitratio>0) {
                            //賺錢才可以+1
                            long_win_count=long_win_count+1;
                        }
                        else{
                            long_win_count=long_win_count;
                        }
                        
                        //勝率
                        if (long_total_count>0) {
                            long_win_ratio= long_win_count/long_total_count*100;
                        }
                        else{
                            long_win_ratio=0;
                        }
                        
                        //做多最大獲利
                        if (realized_trade_long_profitratio>long_max_gain) {
                            long_max_gain=realized_trade_long_profitratio;
                        }
                        
                        //做多最大損失
                        if (realized_trade_long_profitratio<long_max_loss) {
                            long_max_loss=realized_trade_long_profitratio;
                        }
                        
                        
                    }
                    else if (BS_last_unchange==-1){
                        //做空最近一筆 含有交易成本
                        realized_trade_short_profitratio=(enterprice_last_unchange-open)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                        
                        //累計做多
                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                        
                        
                        //累計做空交易次數
                        short_total_count=short_total_count+1;
                        
                        
                        //做空交易賺錢次數
                        if (realized_trade_short_profitratio>0) {
                            //賺錢才可以+1
                            short_win_count=short_win_count+1;
                        }
                        else{
                            short_win_count=short_win_count;
                        }
                        
                        //勝率
                        if (short_total_count>0) {
                            short_win_ratio= short_win_count/short_total_count*100;
                        }
                        else{
                            short_win_ratio=0;
                        }
                        
                        
                        //做空最大獲利
                        if (realized_trade_short_profitratio>short_max_gain) {
                            short_max_gain=realized_trade_short_profitratio;
                        }
                        
                        //做空最大損失
                        if (realized_trade_short_profitratio<short_max_loss) {
                            short_max_loss=realized_trade_short_profitratio;
                        }
                        
                        
                        
                    }
                    
                    //多空合計
                    ls_total_count=long_total_count+short_total_count;
                    ls_win_count=long_win_count+short_win_count;
                    
                    if (ls_total_count>0) {
                        ls_win_ratio=ls_win_count/ls_total_count*100;
                    }
                    else{
                        ls_win_ratio=0;
                    }
                    
                    //多空最大獲利
                    if (realized_trade_long_profitratio>ls_max_gain) {
                        ls_max_gain=realized_trade_long_profitratio;
                    }
                    if (realized_trade_short_profitratio>ls_max_gain) {
                        ls_max_gain=realized_trade_short_profitratio;
                    }
                    //多空最大損失
                    if (realized_trade_long_profitratio<ls_max_loss) {
                        ls_max_loss=realized_trade_long_profitratio;
                    }
                    if (realized_trade_short_profitratio<ls_max_loss) {
                        ls_max_loss=realized_trade_short_profitratio;
                    }
                }
                
                //2.更新最新資料
                BS_last=BS_1;
                enter_price=open;
            }
            
            //有買賣動作之後，本期計算出未實現損益
            if (BS_last  ==1 && enter_price>0) {
                //做多未實現損益
                last_trade_long_profitratio =(close-enter_price)/enter_price*100 ;
            }
            else if(BS_last  == -1 && enter_price>0){
                //做空未實現損益
                last_trade_short_profitratio =(enter_price-close)/enter_price*100 ;
                
            }
            else{
                last_trade_long_profitratio=0;
                last_trade_short_profitratio=0;
                
            }
            
            
            
            //停損機制
            //判斷是否需要停損
            if (isUse_Stop==1) {
                
                
                if (Stop_ratio*-100>last_trade_long_profitratio) {
                    //做多未實現損益超過停損率 下期停損掉
                    BS_Stop=-2;
                }
                else if (Stop_ratio*-100>last_trade_short_profitratio){
                    //做空未實現損益超過停損率 下期停損掉
                    BS_Stop=2;
                    
                }
                
                
            }
            
            
            
            
            
            
            //3.年限
            NSDate *date_0;
            date_0=[his_dic_0 objectForKey:HIS_basic_date];
            
            NSDate  *date_now;
            date_now=[his_dic objectForKey:HIS_basic_date];
            
            double l;
            
            l=[date_now timeIntervalSinceDate:date_0]/86400;
            
            year=l/365;
            
            
            //4.報酬率
            {
                //作多年化報酬率
                return_long=realized_trade_long_profitratio_sum/year;
                
                //作空年化報酬率
                return_short=realized_trade_short_profitratio_sum/year;
                
                //多空年化報酬率
                return_ls=(realized_trade_long_profitratio_sum+realized_trade_short_profitratio_sum)/year;
                
            }
            
        }
        
    }
    
    //7.存入記憶體
    {
        
        //利用字典存資料
        NSMutableDictionary *dic_indicator_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_signal_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_temp_key=[[NSMutableDictionary alloc] init];
        NSMutableDictionary *dic_profit_key=[[NSMutableDictionary alloc] init];
        
        //指標 dic_indicator_key
        {
            
            
            if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:FAMA] forKey:CL_his_data_indicator_MESA1_FAMA];
                [dic_indicator_key setObject:[NSNumber numberWithDouble:MAMA] forKey:CL_his_data_indicator_MESA1_MAMA];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:Period] forKey:CL_his_data_indicator_MESA1_Period];
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:FAMA] forKey:CL_his_data_indicator_MESA2_FAMA];
                [dic_indicator_key setObject:[NSNumber numberWithDouble:MAMA] forKey:CL_his_data_indicator_MESA2_MAMA];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:Period] forKey:CL_his_data_indicator_MESA2_Period];
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:FAMA] forKey:CL_his_data_indicator_MESA3_FAMA];
                [dic_indicator_key setObject:[NSNumber numberWithDouble:MAMA] forKey:CL_his_data_indicator_MESA3_MAMA];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:Period] forKey:CL_his_data_indicator_MESA3_Period];
                
                
            }
            
            
            //添加
            [fdic_indicator setObject:dic_indicator_key forKey:calculate_key];
            
            [dic_indicator_key release];
            
        }
        
        //訊號 dic_signal_key
        {
            
            if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_MESA1_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_MESA1_State];
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_MESA1_BS_Stop];
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_MESA2_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_MESA2_State];
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_MESA2_BS_Stop];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_MESA3_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_MESA3_State];
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_MESA3_BS_Stop];
            }
            
            //添加
            [fdic_signal setObject:dic_signal_key forKey:calculate_key];
            [dic_signal_key release];
        }
        
        //損益 dic_profit_key （已經實現損益與未實現損益 存放所有的序列 至於其他的損益數據就採用暫存模式存放）
        {
            
            //最後一筆買賣尚未實現損益報酬率
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_MESA1_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_MESA1_shortratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_MESA1_longshortratio_lasttrade];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_MESA2_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_MESA2_shortratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_MESA2_longshortratio_lasttrade];
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_MESA3_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_MESA3_shortratio_lasttrade];
                    
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_MESA3_longshortratio_lasttrade];
                }
            }
            //已經實現損益報酬率合計
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA1_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA1_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA1_longshortratio_realizedtrade];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA2_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA2_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA2_longshortratio_realizedtrade];
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA3_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA3_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA3_longshortratio_realizedtrade];
                    
                }
            }
            
            
            //添加
            [fdic_profit setObject:dic_profit_key forKey:calculate_key];
            [dic_profit_key release];
        }
        
        //temp dic_temp_key
        {
            //指標運算所需要使用
            {
                [dic_temp_key setObject:[NSNumber numberWithDouble:price] forKey:HIS_dic_temp_price];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Smooth] forKey:HIS_dic_temp_Smooth];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Detrender] forKey:HIS_dic_temp_Detrender];
                [dic_temp_key setObject:[NSNumber numberWithDouble: Q1] forKey:HIS_dic_temp_Q1];
                [dic_temp_key setObject:[NSNumber numberWithDouble: l1] forKey:HIS_dic_temp_l1];
                [dic_temp_key setObject:[NSNumber numberWithDouble: jl] forKey:HIS_dic_temp_jl];
                [dic_temp_key setObject:[NSNumber numberWithDouble: jQ] forKey:HIS_dic_temp_jQ];
                [dic_temp_key setObject:[NSNumber numberWithDouble: l2] forKey:HIS_dic_temp_l2];
                [dic_temp_key setObject:[NSNumber numberWithDouble: Q2] forKey:HIS_dic_temp_Q2];
                [dic_temp_key setObject:[NSNumber numberWithDouble: Re] forKey:HIS_dic_temp_Re];
                [dic_temp_key setObject:[NSNumber numberWithDouble:lm] forKey:HIS_dic_temp_lm];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Period] forKey:HIS_dic_temp_Period];
                [dic_temp_key setObject:[NSNumber numberWithDouble:SmoothPeriod] forKey:HIS_dic_temp_SmoothPeriod];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Phase] forKey:HIS_dic_temp_Phase];
                [dic_temp_key setObject:[NSNumber numberWithDouble:DeltaPhase] forKey:HIS_dic_temp_DeltaPhase];
                [dic_temp_key setObject:[NSNumber numberWithDouble:alpha] forKey:HIS_dic_temp_alpha];
                [dic_temp_key setObject:[NSNumber numberWithDouble:FAMA] forKey:HIS_dic_temp_FAMA];
                [dic_temp_key setObject:[NSNumber numberWithDouble:MAMA] forKey:HIS_dic_temp_MAMA];
            }
            
            //損益分析計算需要
            {
                //最後一筆買賣方向
                [dic_temp_key setObject:[NSNumber numberWithInt:BS_last] forKey:HIS_dic_temp_profit_bs];
                //最後一筆進場價位
                [dic_temp_key setObject:[NSNumber numberWithDouble:enter_price] forKey:HIS_dic_temp_profit_enterprice];
            }
            
            //損益分析結果最後一筆輸出
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_MESA1]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA1_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA1_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_MESA1_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_MESA1_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_MESA1_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_MESA1_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_MESA1_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_MESA1_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_MESA1_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_MESA1_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_MESA1_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_MESA1_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_MESA1_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_MESA1_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_MESA1_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_MESA1_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_MESA1_LS_max_loss_temp];
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA1_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA1_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA1_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_MESA1_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_MESA1_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_MESA1_LS_return_temp];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_MESA2]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA2_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA2_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_MESA2_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_MESA2_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_MESA2_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_MESA2_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_MESA2_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_MESA2_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_MESA2_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_MESA2_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_MESA2_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_MESA2_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_MESA2_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_MESA2_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_MESA2_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_MESA2_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_MESA2_LS_max_loss_temp];
                    
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA2_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA2_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA2_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_MESA2_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_MESA2_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_MESA2_LS_return_temp];
                    
                    
                }
                else   if ([calculate_key isEqualToString:Defaults_Calculate_MESA3]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA3_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA3_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_MESA3_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_MESA3_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_MESA3_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_MESA3_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_MESA3_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_MESA3_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_MESA3_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_MESA3_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_MESA3_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_MESA3_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_MESA3_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_MESA3_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_MESA3_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_MESA3_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_MESA3_LS_max_loss_temp];
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA3_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA3_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA3_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_MESA3_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_MESA3_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_MESA3_LS_return_temp];
                    
                }
                
                
            }
            
            //添加
            [fdic_temp setObject:dic_temp_key forKey:calculate_key];
            [dic_temp_key release];
            
        }
        
    }
    
}




//計算方法函數 LFMESA
-(void)calculateFunction_LFMESA:(NSString *)calculate_key fhisDa:(NSMutableArray *)fhisDa index:(int)i fdic_indicator:(NSMutableDictionary *)fdic_indicator fdic_signal:(NSMutableDictionary *)fdic_signal fdic_temp:(NSMutableDictionary *)fdic_temp fdic_profit:(NSMutableDictionary *)fdic_profit{
    
    
    //1.計算出MESA Period
    float  price,Period_Mesa ;
    float  Smooth,Detrender ,Q1,l1,jl,jQ,l2,Q2,Re,lm,SmoothPeriod,Phase,DeltaPhase;
    {
        
        //1.開高收低 基本每筆資料
        double  high,low,open,close ;
        
        NSMutableDictionary *his_dic;
        {
            his_dic=[fhisDa objectAtIndex:i];
            
            //調整收盤價比率
            double adj_ratio;
            {
                double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
                double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                
                
                if (isUseAdjClose==YES) {
                    adj_ratio=adj_close/close;
                }
                else{
                    adj_ratio=1;
                }
            }
            
            
            
            
            high=[[his_dic objectForKey:HIS_basic_high] doubleValue] * adj_ratio;
            low=[[his_dic objectForKey:HIS_basic_low] doubleValue]   * adj_ratio;
            open=[[his_dic objectForKey:HIS_basic_open] doubleValue] * adj_ratio;
            close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
            
            
            
            
        }
        
        
        //2.計算用的變數
        
        {
            
            Phase=0;
            
        }
        
        //3.參數
       
                
        //4.計算MESA
        {
            price =(high +low)/2;
            
            
            Smooth =(4 * price + 3 *[self get_his_temp_value:HIS_dic_temp_price calculate_key:calculate_key i:i-1 historyData:fhisDa]  + 2 * [self get_his_temp_value:HIS_dic_temp_price calculate_key:calculate_key i:i-2 historyData:fhisDa] + [self get_his_temp_value:HIS_dic_temp_price calculate_key:calculate_key i:i-3 historyData:fhisDa])/10;
            
                        
            
            
            Detrender=(0.0962*Smooth+0.5769*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-2 historyData:fhisDa] -0.5769*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-4 historyData:fhisDa]-0.0962*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54);
            
            Q1 =(0.0962*Detrender +0.5769*[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-2 historyData:fhisDa]-0.5769*[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-4 historyData:fhisDa]-0.0962*[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54);
            
            l1 =[self get_his_temp_value:HIS_dic_temp_Detrender calculate_key:calculate_key i:i-3 historyData:fhisDa];
            jl=(0.0962*l1+0.5769*[self get_his_temp_value:HIS_dic_temp_l1 calculate_key:calculate_key i:i-2 historyData:fhisDa]-0.5769*[self get_his_temp_value:HIS_dic_temp_l1 calculate_key:calculate_key i:i-4 historyData:fhisDa]-.0962*[self get_his_temp_value:HIS_dic_temp_l1 calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54);
            
            jQ=(0.0962*Q1+.5769*[self get_his_temp_value:HIS_dic_temp_Q1 calculate_key:calculate_key i:i-2 historyData:fhisDa]-.5769*[self get_his_temp_value:HIS_dic_temp_Q1 calculate_key:calculate_key i:i-4 historyData:fhisDa]-0.0962*[self get_his_temp_value:HIS_dic_temp_Q1 calculate_key:calculate_key i:i-6 historyData:fhisDa])*(0.075*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa]+0.54) ;
            
            l2=l1-jQ;
            Q2=Q1+jl;
            
            l2=0.2*l2 +0.8*[self get_his_temp_value:HIS_dic_temp_l2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
            Q2=0.2*Q2+0.8*[self get_his_temp_value:HIS_dic_temp_Q2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            Re =l2 *[self get_his_temp_value:HIS_dic_temp_l2 calculate_key:calculate_key i:i-1 historyData:fhisDa]+Q2*[self get_his_temp_value:HIS_dic_temp_Q2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
            lm=l2*[self get_his_temp_value:HIS_dic_temp_Q2 calculate_key:calculate_key i:i-1 historyData:fhisDa]-Q2*[self get_his_temp_value:HIS_dic_temp_l2 calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            Re =0.2*Re +0.8*[self get_his_temp_value:HIS_dic_temp_Re calculate_key:calculate_key i:i-1 historyData:fhisDa];
            lm=0.2*lm+0.8*[self get_his_temp_value:HIS_dic_temp_lm calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            
            if( lm  !=0 && Re !=0 )
            {
                Period_Mesa = 360/(atan((lm /Re ))*180/(4*atan(1)));
                
            }
            else {
                Period_Mesa=0;
            }
            if( Period_Mesa >1.5*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa])
                Period_Mesa =1.5*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            if(Period_Mesa <0.67*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa])
                Period_Mesa =0.67*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            
            if(Period_Mesa <6)
                Period_Mesa =6;
            if(Period_Mesa >50)
                Period_Mesa =50;
            
                        
            
            Period_Mesa =0.2*Period_Mesa +0.8*[self get_his_temp_value:HIS_dic_temp_Period calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            
            SmoothPeriod =0.33*Period_Mesa +0.67*[self get_his_temp_value:HIS_dic_temp_Smooth calculate_key:calculate_key i:i-1 historyData:fhisDa];
            
            if( l1  !=0 )
                Phase =atan(Q1 /l1 )*180/(4*atan(1));
            
            DeltaPhase=[self get_his_temp_value:HIS_dic_temp_Phase calculate_key:calculate_key i:i-1 historyData:fhisDa]-Phase ;
            
            
             
            	
        }
        
    
    
    }
    
    //2.移動均線
    float ma_fast,ma_slow;
    BOOL fastCrossSlow;
    BOOL isRealFisrtEnter=NO; //是否第一次進場
    {
        ma_fast= 0;
        ma_slow= 0;
        
        
        //如果有前期的判斷值就用前一期的判斷值
        if ([self get_his_temp_NSNumber:HIS_dic_temp_MA_fastCrossSlow calculate_key:calculate_key i:i-1  historyData:fhisDa ]  ) {
            
            fastCrossSlow=[[self get_his_temp_NSNumber:HIS_dic_temp_MA_fastCrossSlow calculate_key:calculate_key i:i-1  historyData:fhisDa ] boolValue];
        }
        else{
            
            fastCrossSlow=NO;
            
        }
        
        //判斷均線是否交叉
        {
            //只有在均線尚未出現交叉訊號之前 才需要計算均線
            if (fastCrossSlow==NO) {
                
                
                int ma_period_short=10;
                int ma_period_long=20;
                
                //限制移動均線的週期
                if (i>ma_period_long) {
                    
                    float sumfast=0;
                    float sumslow=0;
                    
                    for (int is=0; is<ma_period_short;is++ ) {
                        NSMutableDictionary *his_dic;
                        his_dic=[fhisDa objectAtIndex:i];
                        double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                        sumfast=sumfast+close;
                    }
                    
                    
                    for (int is=0; is<ma_period_long;is++ ) {
                        NSMutableDictionary *his_dic;
                        his_dic=[fhisDa objectAtIndex:i];
                        double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                        sumslow=sumslow+close;
                    }
                    
                    //移動均線值
                    ma_fast=sumfast/ma_period_short;
                    ma_slow=sumslow/ma_period_long;
                    
                    //前一期移動均線值
                    float ma_fast_1= [self get_his_temp_value:HIS_dic_temp_MA_Fast calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                    float ma_slow_1= [self get_his_temp_value:HIS_dic_temp_MA_Slow calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                    //判斷短天期均線是否穿越長天期均線
                    if (ma_fast>ma_slow && ma_fast_1<ma_slow_1) {
                        fastCrossSlow=YES;
                        isRealFisrtEnter=YES;
                    }
                    
                    
                    
                }
            }
            
            
            
            
            
            
        }
    } 
    
    //3.開高收低 基本每筆資料
    double   open,close ;
    NSDate   *dates;
    NSMutableDictionary *his_dic;
    {
        his_dic=[fhisDa objectAtIndex:i];
        
        //調整收盤價比率
        double adj_ratio;
        {
            double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
            double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
            dates=[his_dic objectForKey:HIS_basic_date ];
            
            if (isUseAdjClose==YES) {
                adj_ratio=adj_close/close;
            }
            else{
                adj_ratio=1;
            }
        }
        
        
        
        
        //high=[[his_dic objectForKey:HIS_basic_high] doubleValue] * adj_ratio;
        //low=[[his_dic objectForKey:HIS_basic_low] doubleValue]   * adj_ratio;
        open=[[his_dic objectForKey:HIS_basic_open] doubleValue] * adj_ratio;
        close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
        
        
        
        
    }
    
    //4.參數
    float Bratio,Sratio,Pratio;
    int long_Nday,short_Nday;
    int add_limit=1;         //加碼上限
    
    float long_cost,short_cost; //交易成本
    float Stop_ratio;           //停損率
    int   isUse_Stop;             //是否停損
    float Period=Period_Mesa ;
    
    //int para_add_limit=1;//加碼上限
    
    {
        
        //取出參數存放位置字典
        NSString *DWM;
        NSMutableDictionary *para_dic_all  ;
        NSMutableDictionary *para_dic_all_method ;//取出特定方法下的參數值
        NSMutableDictionary *para_dic; //取出特定週期的參數值
        
        DWM=day; //!!!!!!! 很重要目前是以日線參數來進行計算
        
        para_dic_all=  [[self data_object_para] Para_calculate_method:calculate_key period:DWM]  ;
        
        para_dic_all_method=[para_dic_all objectForKey:calculate_key ];
        para_dic=[para_dic_all_method objectForKey:day];
        
        Bratio   =[[para_dic objectForKey:Para_1] floatValue];
        Sratio   =[[para_dic objectForKey:Para_2] floatValue];
        Pratio    =[[para_dic objectForKey:Para_3] floatValue];
        add_limit    =[[para_dic objectForKey:Para_4] intValue];
        
        //避免買入限制低於0
        if (add_limit<=0) {
            add_limit=1;
        }
        
        
        
        if ((int)(Period * Pratio)>1) {
            long_Nday    =(int)(Period * Pratio);
            short_Nday   =(int)(Period * Pratio);
        }
        else{
            long_Nday    =1;
            short_Nday   =1;
        }
       
        
        long_cost =[[para_dic objectForKey:Para_Optimize_long_cost ] floatValue];
        short_cost=[[para_dic objectForKey:Para_Optimize_short_cost ] floatValue];
        Stop_ratio=[[para_dic objectForKey:Para_Optimize_Stop_ratio ] floatValue];
        isUse_Stop=[[para_dic objectForKey:Para_Optimize_isUse_Stop ] intValue];
        
        
    }
    
    //5.計算
    float LFMESA_bout;
    float LFMESA_sout;
    
    int LFMESA_b;
    int LFMESA_s;
    int LFMESA_b_1;
    int LFMESA_s_1;
    
    int long_step_count;
    int short_step_count;
    
    int long_step_count_no_limit;
    int long_step_count_Max; //歷史上買進加碼次數最大值
    
    int Add_Long_Signal=0;//是否加碼買入訊號 1:表示加碼 0:表示沒有動作
    int Add_Long_Signal_ExcessMax=0;//是否超過歷史加碼買入訊號 1:表示加碼 0:表示沒有動作
    
    BOOL isAdd_long_step_count=NO; //是否有做多加碼
    BOOL isAdd_short_step_count=NO;//是否有做空加碼
    
    
    {
            
            if (i>=1) {
                LFMESA_bout= [self get_his_temp_value:HIS_dic_temp_LFMESA_bout calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LFMESA_sout= [self get_his_temp_value:HIS_dic_temp_LFMESA_sout calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LFMESA_b=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_b calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LFMESA_s=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_s calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                //紀錄上一期
                LFMESA_b_1=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_b calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                LFMESA_s_1=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_s calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                
                
                //摺疊次數
                long_step_count=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_long_step_count calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                //無限制
                 long_step_count_no_limit=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_long_step_count_no_limit calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                
                //做多加碼次數歷史最大值
                 long_step_count_Max=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_long_step_Max calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                short_step_count=(int) [self get_his_temp_value:HIS_dic_temp_LFMESA_short_step_cpont calculate_key:calculate_key i:i-1 historyData:fhisDa];
                
                
            }
            else{
                
                LFMESA_bout=0;
                LFMESA_sout=0;
                LFMESA_b=0;
                LFMESA_s=0;
                LFMESA_b_1=0;
                LFMESA_s_1=0;
                long_step_count=0;
                long_step_count_no_limit=0;
                long_step_count_Max=999; //初始值表示都沒有開始計算
                
                short_step_count=0;
                
            }
            
            
            int start_i;
            {
                if (long_Nday>short_Nday) {
                    start_i=long_Nday;
                }
                else{
                    start_i=short_Nday;
                }
                
                
            }
            
            //做多區間
            float BRange;
            {
                float rhigh=0;
                float rlow=0;
                {
                    //區間最大值
                    for (int Hi=0;Hi<long_Nday ; Hi++) {
                        
                        if (Hi==0) {
                            
                            rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                        }
                        else{
                            if (i-Hi>=0 && i-Hi<[fhisDa count]) {
                                if (rhigh<[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                    
                                    rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                    
                                }
                                
                                
                            }
                            
                                                       
                            
                        }
                        
                    }
                    
                    //區間最小值
                    for (int Li=0;Li<long_Nday ; Li++) {
                        
                        if (Li==0) {
                            
                            rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                        }
                        else{
                            if (i-Li>=0 && i-Li<[fhisDa count]) {
                                if (rlow>[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                    
                                    rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                    
                                }
                                
                                
                                
                            }
                            
                            
                            
                                                        
                            
                        }
                        
                    }
                    
                    
                    
                }
                BRange=rhigh-rlow;
            }
            
            //做空區間
            float SRange;
            {
                float rhigh=0;
                float rlow=0;
                {
                    //區間最大值
                    for (int Hi=0;Hi<short_Nday ; Hi++) {
                        
                        if (Hi==0) {
                            
                            rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                        }
                        else{
                            if (i-Hi>=0 && i-Hi<[fhisDa count]) {
                                if (rhigh<[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                    
                                    rhigh=[[[fhisDa objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                    
                                }
                                
                                
                            }
                            
                            
                            
                                                       
                            
                        }
                        
                    }
                    
                    //區間最小值
                    for (int Li=0;Li<short_Nday ; Li++) {
                        
                        if (Li==0) {
                            
                            rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                        }
                        else{
                            if (i-Li>=0 && i-Li<[fhisDa count]) {
                                if (rlow>[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                    
                                    rlow=[[[fhisDa objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                    
                                }
                                
                                
                            }
                            
                            
                                                        
                            
                        }
                        
                    }
                    
                    
                }
                
                SRange=rhigh-rlow;
            }
            
            
            
            
            {
                
                float close=[[[fhisDa objectAtIndex:i] objectForKey:HIS_basic_adjclose] doubleValue];
                
                
                //第一次進場
                if (LFMESA_b==0 && LFMESA_s==0 && fastCrossSlow==YES ) {
                 
                    LFMESA_b=1;
                    LFMESA_s=0;
                    LFMESA_bout=close-BRange*Bratio;
                    LFMESA_sout=0;
                    
                    long_step_count=1;
                    long_step_count_no_limit=1;
                    short_step_count=0;
                }
                //做多且價格上移突破
                else if (LFMESA_b==1 && LFMESA_bout+BRange<close) {
                    LFMESA_bout=LFMESA_bout+BRange*Bratio;
                    
                    //限制做多加碼上限
                    if (add_limit > long_step_count) {
                        
                        long_step_count=long_step_count+1;
                       
                        isAdd_long_step_count=YES;
                        
                        //突破顯示訊號
                        Add_Long_Signal=1;
                       
                    }
                    
                    long_step_count_no_limit=long_step_count_no_limit+1;
                    
                    //是否有超過歷史最大加碼次數
                    {
                    
                        if (long_step_count_Max<long_step_count_no_limit) {
                            //突破歷史最大顯示訊號
                            Add_Long_Signal_ExcessMax=1;
                        }
                    
                    }
                    
                    
                    
                }
                //做多且價格向下跌破
                else if (LFMESA_b==1 && close<LFMESA_bout) {
                   
                    //檢查比較最近3年來 歷史最大摺疊次數
                    {
                        NSDate *now=dates;
                        
                        int _year=3;//重要越長表示越不會出現加碼訊號
                        
                        NSTimeInterval ti;
                        ti=-1*60*60*24*365*_year;//  往前推10年資料下載
                        
                        NSDate *start_date=[NSDate dateWithTimeInterval:ti sinceDate: [NSDate date]];
                        
                        
                        if ([now compare:start_date ]==NSOrderedDescending   ) {
                            
                            //從此刻開始
                            if (long_step_count_Max==999) {
                                long_step_count_Max=0;
                            }
                            
                            
                            if (long_step_count_no_limit>long_step_count_Max) {
                                long_step_count_Max=long_step_count_no_limit;
                            }
                            
                        }

                        
                                           
                    }
                    
                    
                    LFMESA_b=0;
                    LFMESA_s=1;
                    LFMESA_sout=close+SRange*Sratio;
                    LFMESA_bout=0;
                    
                    long_step_count=0;
                    long_step_count_no_limit=0;
                    
                    short_step_count=1;
                    
                    
                    
                }
                //做空且價格向下移動
                else if (LFMESA_s==1 && LFMESA_sout-SRange>close) {
                    LFMESA_sout=LFMESA_sout-SRange*Sratio;
                    
                    //限制做空加碼上限
                    if (add_limit > short_step_count) {
                        
                        short_step_count=short_step_count+1;
                         
                        isAdd_short_step_count=YES;
                    }
                    
                    
                   
                    
                    
                    
                }
                //做空且價格向上突破
                else if (LFMESA_s==1 && close>LFMESA_sout) {
                    LFMESA_s=0;
                    LFMESA_b=1;
                    LFMESA_bout=close-BRange*Bratio;
                    LFMESA_sout=0;
                    
                    
                    long_step_count=1;
                    long_step_count_no_limit=1;
                    
                    short_step_count=0;
                }
                
                
                
            }
            
            
            
        }
    
    //6.訊號判斷
    int BuyOrSell;      //此位置 i 是否要買或賣
    int Position_State; //此位置 i 多空狀態
    int BS_Stop; //停損機制 2表示做空停損 -2表示做多停損
    
    {
        BuyOrSell=0;
        Position_State=0;
        BS_Stop=0;
                
        if (i>0) {
            
            //買賣訊號
            if (LFMESA_b_1==1 && LFMESA_s==1) {
                BuyOrSell=-1;
                
            }
            else if ( (LFMESA_s_1==1 && LFMESA_b==1) ||  isRealFisrtEnter==YES ) {
                BuyOrSell=1;
            }
            else {
                BuyOrSell=0;
            }
            
            //狀態
            if (LFMESA_s==1) {
                Position_State=-1;
            }
            else {
                Position_State=1;
            }
            
            
        }
        
        
    }
    
    //7.損益部位
    double last_trade_long_profitratio;         //最後一筆做多獲利率
    double last_trade_short_profitratio;        //最後一筆做空獲利率
    double realized_trade_long_profitratio;     //已經實現做多損益
    double realized_trade_short_profitratio;    //已經實現做空損益
    double realized_trade_long_profitratio_sum; //已經實現做多損益合計
    double realized_trade_short_profitratio_sum;//已經實現做空損益合計
    
    double profit_single_realize=0;//單筆已經實現損益 檢查用
    double profit_single_unrealize=0;//單筆尚未實現損益 檢查用
    
    
    
    double long_total_count; //做多交易次數
    double long_win_count;   //做多交易賺錢次數
    double long_win_ratio;   //做多勝率
    
    double short_total_count; //做空交易次數
    double short_win_count;   //做空交易賺錢次數
    double short_win_ratio;   //做空勝率
    
    double ls_total_count; //多空交易次數
    double ls_win_count;   //多空交易賺錢次數
    double ls_win_ratio;   //多空勝率
    
    double long_max_gain; //做多最大獲利率
    double long_max_loss; //做多最大虧損率
    double short_max_gain; //做空最大獲利率
    double short_max_loss; //做空最大虧損率
    double ls_max_gain;  //多空最大獲利率
    double ls_max_loss; //多空最大虧損率
    
    double year; //開始計算日期
    
    double return_long;// 作多年化報酬率
    double return_short;// 作空年化報酬率
    double return_ls;// 作空年化報酬率
    
    int BS_last ;// 最後一期買賣方向 因為是以隔天開盤價作為當期買賣價位
    double enter_price; //最後一期買進場價位
    double enter_price_average; //平均買進場價位
    {
        //變數歸0
        {
            last_trade_long_profitratio=0;
            last_trade_short_profitratio=0;
            
            realized_trade_long_profitratio=0;
            realized_trade_short_profitratio=0;
            
            realized_trade_long_profitratio_sum=0;
            realized_trade_short_profitratio_sum=0;
            
            long_total_count=0;
            long_win_count=0;
            long_win_ratio=0;
            
            short_total_count=0;
            short_win_count=0;
            short_win_ratio=0;
            
            ls_total_count=0;
            ls_win_count=0;
            ls_win_ratio=0;
            
            long_max_gain=0; //做多最大獲利率
            long_max_loss=0; //做多最大虧損率
            short_max_gain=0; //做空最大獲利率
            short_max_loss=0; //做空最大虧損率
            ls_max_gain=0;  //多空最大獲利率
            ls_max_loss=0; //多空最大虧損率
            
            
            BS_last=0;
            enter_price=0;
            enter_price_average=0;
            year=0;
            
            return_long=0;
            return_short=0;
            return_ls=0;
        }
        
        
        if (i>0) {
            
            
            int BS_1 ;// 前一期買賣動作方向 因為是以隔天開盤價作為當期買賣價位
            BS_1=0;
            
            //停損機制
            int BS_Stop_1; //前一期是否有出現停損動作
            BS_Stop_1=0;
            
            //1.取出前一期的資料
            NSMutableDictionary *his_dic_1=[fhisDa objectAtIndex:i-1];//前一筆
            NSMutableDictionary *his_dic_0=[fhisDa objectAtIndex:0];  //第0筆
            
            if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA1]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_signal_LFMESA1_BS_Stop] intValue];
                
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_signal_LFMESA1_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_short_win_ratio_temp] doubleValue];
                
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_LS_win_ratio_temp] doubleValue];
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA1] objectForKey:CL_his_data_profit_LFMESA1_LS_max_loss_temp] doubleValue];
                
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA2]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_signal_LFMESA2_BS_Stop] intValue];
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_signal_LFMESA2_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_short_win_ratio_temp] doubleValue];
                
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_LS_win_ratio_temp] doubleValue];
                
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA2] objectForKey:CL_his_data_profit_LFMESA2_LS_max_loss_temp] doubleValue];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA3]) {
                //停損機制
                //前一期是否有出現停損動作
                BS_Stop_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_signal_LFMESA3_BS_Stop] intValue];
                
                
                //前一期 買賣動作方向
                BS_1=[[[[his_dic_1 objectForKey:HIS_dic_signal] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_signal_LFMESA3_BS] intValue];
                
                //前一期 已經實現做多合計
                realized_trade_long_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_longratio_realizedtrade_temp] doubleValue];
                
                //前一期 已經實現做空合計
                realized_trade_short_profitratio_sum=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_shortratio_realizedtrade_temp] doubleValue];
                
                //前一期 做多交易次數
                long_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_long_total_count_temp] doubleValue];
                
                //前一期 做多賺錢交易次數
                long_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_long_win_count_temp] doubleValue];
                
                //前一期 做多勝率
                long_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_long_win_ratio_temp] doubleValue];
                
                
                //前一期 做空交易次數
                short_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_short_total_count_temp] doubleValue];
                
                //前一期 做空賺錢交易次數
                short_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_short_win_count_temp] doubleValue];
                
                //前一期 做空勝率
                short_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_short_win_ratio_temp] doubleValue];
                
                //前一期 多空交易次數
                ls_total_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_LS_total_count_temp] doubleValue];
                
                //前一期 多空賺錢交易次數
                ls_win_count=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_LS_win_count_temp] doubleValue];
                
                //前一期 多空勝率
                ls_win_ratio=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_LS_win_ratio_temp] doubleValue];
                
                //做多最大獲利率
                long_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_long_max_gain_temp] doubleValue];
                
                //做多最大虧損率
                long_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_long_max_loss_temp] doubleValue];
                
                //做空最大獲利率
                short_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_short_max_gain_temp] doubleValue];
                
                //做空最大虧損率
                short_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_short_max_loss_temp] doubleValue];
                
                //多空最大獲利率
                ls_max_gain=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_LS_max_gain_temp] doubleValue];
                
                //多空最大虧損率
                ls_max_loss=[[[[his_dic_1 objectForKey:HIS_dic_temp] objectForKey:Defaults_Calculate_LFMESA3] objectForKey:CL_his_data_profit_LFMESA3_LS_max_loss_temp] doubleValue];
                
                
            }
            
            
            //2.判斷上一期是否有買賣動作
            if (BS_1==0) {
                
                //上一期沒有動作
                //進場成本
                {
                    //第一次進場成本
                    enter_price=[self get_his_temp_value:HIS_dic_temp_profit_enterprice calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                    //平均進場成本
                    {
                       
                        //前一期是否有加碼
                        BOOL isLong_Add_1=[[self get_his_temp_NSNumber:HIS_dic_temp_profit_long_add calculate_key:calculate_key i:i-1 historyData:fhisDa] boolValue];
                        
                        
                        BOOL isShort_Add_1=[[self get_his_temp_NSNumber:HIS_dic_temp_profit_short_add calculate_key:calculate_key i:i-1 historyData:fhisDa] boolValue];
                        
                        
                        
                        if (isLong_Add_1==YES || isShort_Add_1==YES) {
                            
                            //上次進場平均成本
                            enter_price_average=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                            
                            //做多
                            {
                                int long_position_1=(int) [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                                
                                //long_step_count_1=long_step_count_1 ; //尚未加碼前的數字
                                
                                if (isLong_Add_1==YES) {
                                    
                                    enter_price_average=(enter_price_average* long_position_1 +open)/(long_position_1+1);
                                }
                                
                                
                                
                            }
                            //做空
                            {
                                
                                int short_position_1=(int) [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                                
                                short_position_1=short_position_1*-1;
                                
                                if (isShort_Add_1==YES) {
                                    
                                    enter_price_average=(enter_price_average* short_position_1 +open)/(short_position_1+1);
                                }
                                
                                
                                
                                
                            }

                                                       
                            
                            
                        }
                        else{
                        
                            enter_price_average=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                        }
                        
                       
                    
                    }
                   
                }                 
                
                
                //停損機制
                //前一期是否需要停損
                if (BS_Stop_1==-2) {
                    //前一期出現需要做多停損訊號
                    BS_last=0;
                    //作多出場損益
                    {
                        //做多最近一筆 含有交易成本
                        realized_trade_long_profitratio=(open-enter_price)/enter_price*100-(long_cost+short_cost)*100;
                        
                        
                        float enter_price_average_1=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                        
                        
                        float  BS_position_1=  [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                        
                        //部位調整比率用再做資金分配
                        float adjRatio_Position=   BS_position_1/  add_limit ;
                        if (adjRatio_Position<0) {
                            adjRatio_Position=adjRatio_Position*-1;
                        }

                        
                        profit_single_realize=((open-enter_price_average_1)/enter_price_average_1*100- (long_cost+short_cost)*100)*adjRatio_Position;
                        
                        realized_trade_long_profitratio=profit_single_realize;
                        
                        
                        
                        //累計做多
                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                        
                        //累計做多交易次數
                        long_total_count=long_total_count+1;
                        
                        //做多交易賺錢次數
                        if (realized_trade_long_profitratio>0) {
                            //賺錢才可以+1
                            long_win_count=long_win_count+1;
                        }
                        else{
                            long_win_count=long_win_count;
                        }
                        
                        //勝率
                        if (long_total_count>0) {
                            long_win_ratio= long_win_count/long_total_count*100;
                        }
                        else{
                            long_win_ratio=0;
                        }
                        
                        //做多最大獲利
                        if (realized_trade_long_profitratio>long_max_gain) {
                            long_max_gain=realized_trade_long_profitratio;
                        }
                        
                        //做多最大損失
                        if (realized_trade_long_profitratio<long_max_loss) {
                            long_max_loss=realized_trade_long_profitratio;
                        }
                        
                        
                    }
                    
                }
                else if (BS_Stop_1==2){
                    //前一期出現做空需要停損的訊號
                    BS_last=0;
                    //作空出場損益
                    {
                        //做空最近一筆 含有交易成本
                        realized_trade_short_profitratio=(enter_price-open)/enter_price*100-(long_cost+short_cost)*100;
                        
                        float enter_price_average_1=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                        
                        float  BS_position_1=  [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                        
                        //部位調整比率用再做資金分配
                        float adjRatio_Position=   BS_position_1/  add_limit ;
                        if (adjRatio_Position<0) {
                            adjRatio_Position=adjRatio_Position*-1;
                        }

                        
                        profit_single_realize=((open-enter_price_average_1)*-1/enter_price_average_1*100-(long_cost+short_cost)*100)*adjRatio_Position;
                        
                        realized_trade_short_profitratio=profit_single_realize;
                        
                        
                        //累計做多
                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                        
                        
                        //累計做空交易次數
                        short_total_count=short_total_count+1;
                        
                        
                        //做空交易賺錢次數
                        if (realized_trade_short_profitratio>0) {
                            //賺錢才可以+1
                            short_win_count=short_win_count+1;
                        }
                        else{
                            short_win_count=short_win_count;
                        }
                        
                        //勝率
                        if (short_total_count>0) {
                            short_win_ratio= short_win_count/short_total_count*100;
                        }
                        else{
                            short_win_ratio=0;
                        }
                        
                        
                        //做空最大獲利
                        if (realized_trade_short_profitratio>short_max_gain) {
                            short_max_gain=realized_trade_short_profitratio;
                        }
                        
                        //做空最大損失
                        if (realized_trade_short_profitratio<short_max_loss) {
                            short_max_loss=realized_trade_short_profitratio;
                        }
                    }
                    
                }
                else{
                    //表示上一期無買賣動作
                    //取出最後一筆的狀態 在轉移到下一期
                    BS_last= [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                    BOOL isAdd_long_step_count_1= [[self get_his_temp_NSNumber: HIS_dic_temp_profit_long_add calculate_key:calculate_key i:i-1 historyData:fhisDa] boolValue];
                                       
                    //考慮加碼來增加多方或是空方部位
                    if (isAdd_long_step_count_1==YES) {
                        
                        if (BS_last>0) {
                        
                            //表示是有多單部位狀態才可以加多
                            BS_last=BS_last+1;
                        }
                       
                    }
                    
                    
                    BOOL isAdd_short_step_count_1= [[self get_his_temp_NSNumber: HIS_dic_temp_profit_short_add calculate_key:calculate_key i:i-1 historyData:fhisDa] boolValue];
                    
                    
                    if (isAdd_short_step_count_1==YES) {
                       
                        if (BS_last<0) {
                           //表示是有空頭部位的情況下才加空
                            BS_last=BS_last-1;
                        }
                        
                        
                      
                    }

                    
                    
                }
                
                
            }
            else{
                //表示上一期有買賣動作
                
                //1.計算已經實現損益
                {
                    //上一期尚未動作之前的部位
                    int BS_last_unchange;        //上一期的部位方向
                    double enterprice_last_unchange;//上一期的部位的進場價格還尚未更新到本期的開盤價之前的資料
                    
                    BS_last_unchange=[self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    enterprice_last_unchange=[self get_his_temp_value:HIS_dic_temp_profit_enterprice calculate_key:calculate_key i:i-1 historyData:fhisDa];
                    
                  
                    int iBS_position_1=  [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                                       
                    
                    //計算已經實現損益與累計實現損益
                    if (iBS_position_1>0) {
                        
                        //做多最近一筆 含有交易成本
                        // realized_trade_long_profitratio=(open-enterprice_last_unchange)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                        float  BS_position_1=  [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                        
                        //部位調整比率用再做資金分配
                        float adjRatio_Position=   BS_position_1/  add_limit ;
                        if (adjRatio_Position<0) {
                            adjRatio_Position=adjRatio_Position*-1;
                        } 
                        
                        
                        
                        float enter_price_average_1=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                                             
                        
                        profit_single_realize=((open-enter_price_average_1)/enter_price_average_1*100-(long_cost+short_cost)*100)*adjRatio_Position;
                        
                      
                        realized_trade_long_profitratio=profit_single_realize;
                        
                        
                        //NSLog(@"%f %f",open,enterprice_last_unchange);
                        //NSLog(@"realized %@=%f",dates,realized_trade_long_profitratio);
                        
                        //累計做多
                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                        
                        //累計做多交易次數
                        long_total_count=long_total_count+1;
                        
                        //做多交易賺錢次數
                        if (realized_trade_long_profitratio>0) {
                            //賺錢才可以+1
                            long_win_count=long_win_count+1;
                        }
                        else{
                            long_win_count=long_win_count;
                        }
                        
                        //勝率
                        if (long_total_count>0) {
                            long_win_ratio= long_win_count/long_total_count*100;
                        }
                        else{
                            long_win_ratio=0;
                        }
                        
                        //做多最大獲利
                        if (realized_trade_long_profitratio>long_max_gain) {
                            long_max_gain=realized_trade_long_profitratio;
                        }
                        
                        //做多最大損失
                        if (realized_trade_long_profitratio<long_max_loss) {
                            long_max_loss=realized_trade_long_profitratio;
                        }
                        
                        
                    }
                    else if (iBS_position_1<0){
                        //做空最近一筆 含有交易成本
                         //realized_trade_short_profitratio=(enterprice_last_unchange-open)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                        
                        float  BS_position_1=  [self get_his_temp_value:HIS_dic_temp_profit_bs calculate_key:calculate_key i:i-1 historyData:fhisDa] ;
                        
                        //部位調整比率用再做資金分配
                        float adjRatio_Position=   BS_position_1/  add_limit ;
                        if (adjRatio_Position<0) {
                            adjRatio_Position=adjRatio_Position*-1;
                        }

                        
                        
                        
                        float enter_price_average_1=[self get_his_temp_value:HIS_dic_temp_profit_enterprice_average calculate_key:calculate_key i:i-1 historyData:fhisDa];
                                              
                        
                        profit_single_realize=((open-enter_price_average_1)*-1/enter_price_average_1*100-(long_cost+short_cost)*100 )*adjRatio_Position;
                        
                        
                        realized_trade_short_profitratio=profit_single_realize;
                        
                        
                        //累計做多
                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                        
                        
                        //累計做空交易次數
                        short_total_count=short_total_count+1;
                        
                        
                        //做空交易賺錢次數
                        if (realized_trade_short_profitratio>0) {
                            //賺錢才可以+1
                            short_win_count=short_win_count+1;
                        }
                        else{
                            short_win_count=short_win_count;
                        }
                        
                        //勝率
                        if (short_total_count>0) {
                            short_win_ratio= short_win_count/short_total_count*100;
                        }
                        else{
                            short_win_ratio=0;
                        }
                        
                        
                        //做空最大獲利
                        if (realized_trade_short_profitratio>short_max_gain) {
                            short_max_gain=realized_trade_short_profitratio;
                        }
                        
                        //做空最大損失
                        if (realized_trade_short_profitratio<short_max_loss) {
                            short_max_loss=realized_trade_short_profitratio;
                        }
                        
                        
                        
                    }
                 
                  //  profit_single_realize=BS_position_1/add_limit;
                   // NSLog(@"profit_single_realize=%f BS_position_1=%f",profit_single_realize ,BS_position_1);
                    
                    //多空合計
                    ls_total_count=long_total_count+short_total_count;
                    ls_win_count=long_win_count+short_win_count;
                    
                    if (ls_total_count>0) {
                        ls_win_ratio=ls_win_count/ls_total_count*100;
                    }
                    else{
                        ls_win_ratio=0;
                    }
                    
                    //多空最大獲利
                    if (realized_trade_long_profitratio>ls_max_gain) {
                        ls_max_gain=realized_trade_long_profitratio;
                    }
                    if (realized_trade_short_profitratio>ls_max_gain) {
                        ls_max_gain=realized_trade_short_profitratio;
                    }
                    //多空最大損失
                    if (realized_trade_long_profitratio<ls_max_loss) {
                        ls_max_loss=realized_trade_long_profitratio;
                    }
                    if (realized_trade_short_profitratio<ls_max_loss) {
                        ls_max_loss=realized_trade_short_profitratio;
                    }
                }
                
                //2.更新最新資料
                BS_last=BS_1;
                enter_price=open;
                enter_price_average=open;
            }
            
            //有買賣動作之後，本期計算出未實現損益
            if (BS_last  > 0 && enter_price_average>0) {
                //做多未實現損益
                //last_trade_long_profitratio =(close-enter_price)/enter_price*100 ;
              
                //不考慮資金使用效率 所以不處理部位比例
                profit_single_unrealize=(close-enter_price_average)/enter_price_average*1*100;
                
                last_trade_long_profitratio=profit_single_unrealize;
                
            }
            else if(BS_last  < 0 && enter_price_average>0){
                //做空未實現損益
                //last_trade_short_profitratio =(enter_price-close)/enter_price*100 ;
               
                profit_single_unrealize=(close-enter_price_average)/enter_price_average*-1*100;
                
                last_trade_short_profitratio=profit_single_unrealize;
            
            }
            else{
                last_trade_long_profitratio=0;
                last_trade_short_profitratio=0;
                
            }
            
            
            
            //停損機制
            //判斷是否需要停損
            if (isUse_Stop==1) {
                
                
                if (Stop_ratio*-100>last_trade_long_profitratio) {
                    //做多未實現損益超過停損率 下期停損掉
                    BS_Stop=-2;
                }
                else if (Stop_ratio*-100>last_trade_short_profitratio){
                    //做空未實現損益超過停損率 下期停損掉
                    BS_Stop=2;
                    
                }
                
                
            }
            
            
            
            
            
            
            //3.年限
            NSDate *date_0;
            date_0=[his_dic_0 objectForKey:HIS_basic_date];
            
            NSDate  *date_now;
            date_now=[his_dic objectForKey:HIS_basic_date];
            
            double l;
            
            l=[date_now timeIntervalSinceDate:date_0]/86400;
            
            year=l/365;
            
            
            //4.報酬率
            {
                //作多年化報酬率
                return_long=realized_trade_long_profitratio_sum/year;
                
                //作空年化報酬率
                return_short=realized_trade_short_profitratio_sum/year;
                
                //多空年化報酬率
                return_ls=(realized_trade_long_profitratio_sum+realized_trade_short_profitratio_sum)/year;
                
            }
            
        }
        
    }
    
    //8.存入記憶體
    {   
        //指標
        {            
            NSMutableDictionary *dic_indicator_key=[[NSMutableDictionary alloc] init];
            
            if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA1]){
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LFMESA_bout] forKey:CL_his_data_indicator_LFMESA1_Long_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LFMESA_sout] forKey:CL_his_data_indicator_LFMESA1_Short_StopPrice];
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:long_step_count ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Count];
                
                 [dic_indicator_key setObject:[NSNumber numberWithDouble:long_step_count_no_limit ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Count_No_Limit];
                
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:short_step_count ] forKey:CL_his_data_indicator_LFMESA1_Short_Step_Count];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:Period] forKey:CL_his_data_indicator_LFMESA1_Period];
                
                //加碼上限
                [dic_indicator_key setObject:[NSNumber numberWithInt:add_limit ] forKey:CL_his_data_indicator_LFMESA1_Add_Limit];
                
                //最近幾年來 加碼最大值 
                [dic_indicator_key setObject:[NSNumber numberWithInt:long_step_count_Max ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Max];
               
                //超過加碼最大值的次數
                 
                if (long_step_count_Max<long_step_count_no_limit) {
                    
                    [dic_indicator_key setObject:[NSNumber numberWithInt:long_step_count_no_limit-long_step_count_Max ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Excess_Max];
                }
                else{
                    
                    
                    [dic_indicator_key setObject:[NSNumber numberWithInt:0 ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Excess_Max];
                    
                    
                }

                //預測做多進場可能損失
                if (LFMESA_bout>0) {
                    
                    float lostRatio=(close-LFMESA_bout)/LFMESA_bout*100;
                   
                    [dic_indicator_key setObject:[NSNumber numberWithDouble:lostRatio] forKey:CL_his_data_indicator_LFMESA1_Long_ForcastLost];
                }
                else{
                    [dic_indicator_key setObject:[NSNumber numberWithDouble:0] forKey:CL_his_data_indicator_LFMESA1_Long_ForcastLost];
                }
               
                

                                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA2]){
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LFMESA_bout] forKey:CL_his_data_indicator_LFMESA2_Long_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LFMESA_sout] forKey:CL_his_data_indicator_LFMESA2_Short_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:long_step_count ] forKey:CL_his_data_indicator_LFMESA2_Long_Step_Count];
                
                 [dic_indicator_key setObject:[NSNumber numberWithDouble:long_step_count_no_limit ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Count_No_Limit];
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:short_step_count ] forKey:CL_his_data_indicator_LFMESA2_Short_Step_Count];
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:Period] forKey:CL_his_data_indicator_LFMESA2_Period];
                
                
                //加碼上限
                [dic_indicator_key setObject:[NSNumber numberWithInt:add_limit ] forKey:CL_his_data_indicator_LFMESA2_Add_Limit];
                //加碼最大值
                [dic_indicator_key setObject:[NSNumber numberWithInt:long_step_count_Max ] forKey:CL_his_data_indicator_LFMESA2_Long_Step_Max];
                
                
                //超過加碼最大值的次數
                if (long_step_count_Max<long_step_count_no_limit) {
                    
                    [dic_indicator_key setObject:[NSNumber numberWithInt:long_step_count_no_limit-long_step_count_Max ] forKey:CL_his_data_indicator_LFMESA2_Long_Step_Excess_Max];
                }
                else{
                    
                    
                    [dic_indicator_key setObject:[NSNumber numberWithInt:0 ] forKey:CL_his_data_indicator_LFMESA2_Long_Step_Excess_Max];
                    
                    
                }

                //預測做多進場可能損失
                if (LFMESA_bout>0) {
                    
                    float lostRatio=(close-LFMESA_bout)/LFMESA_bout*100;
                    
                    [dic_indicator_key setObject:[NSNumber numberWithDouble:lostRatio] forKey:CL_his_data_indicator_LFMESA2_Long_ForcastLost];
                }
                else{
                    [dic_indicator_key setObject:[NSNumber numberWithDouble:0] forKey:CL_his_data_indicator_LFMESA2_Long_ForcastLost];
                }
                

                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA3]){
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LFMESA_bout] forKey:CL_his_data_indicator_LFMESA3_Long_StopPrice];
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:LFMESA_sout] forKey:CL_his_data_indicator_LFMESA3_Short_StopPrice];
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:long_step_count ] forKey:CL_his_data_indicator_LFMESA3_Long_Step_Count];
                
                 [dic_indicator_key setObject:[NSNumber numberWithDouble:long_step_count_no_limit ] forKey:CL_his_data_indicator_LFMESA1_Long_Step_Count_No_Limit];
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:short_step_count ] forKey:CL_his_data_indicator_LFMESA3_Short_Step_Count];
                
                
                [dic_indicator_key setObject:[NSNumber numberWithDouble:Period] forKey:CL_his_data_indicator_LFMESA3_Period];
                
                //加碼上限
                [dic_indicator_key setObject:[NSNumber numberWithInt: add_limit ] forKey:CL_his_data_indicator_LFMESA3_Add_Limit];
                
                //加碼最大值
                [dic_indicator_key setObject:[NSNumber numberWithInt:long_step_count_Max ] forKey:CL_his_data_indicator_LFMESA3_Long_Step_Max];
                
                //超過加碼最大值的次數
                 
                if (long_step_count_Max<long_step_count_no_limit) {
                  
                    
                    
                    [dic_indicator_key setObject:[NSNumber numberWithInt:long_step_count_no_limit-long_step_count_Max ] forKey:CL_his_data_indicator_LFMESA3_Long_Step_Excess_Max];
                }
                else{
                    
                    
                    [dic_indicator_key setObject:[NSNumber numberWithInt:0 ] forKey:CL_his_data_indicator_LFMESA3_Long_Step_Excess_Max];
                    
                    
                }

                
                //預測做多進場可能損失
                if (LFMESA_bout>0) {
                    
                    float lostRatio=(close-LFMESA_bout)/LFMESA_bout*100;
                    
                    [dic_indicator_key setObject:[NSNumber numberWithDouble:lostRatio] forKey:CL_his_data_indicator_LFMESA3_Long_ForcastLost];
                }
                else{
                    [dic_indicator_key setObject:[NSNumber numberWithDouble:0] forKey:CL_his_data_indicator_LFMESA3_Long_ForcastLost];
                }
                

            }
             
            //添加
            [fdic_indicator setObject:dic_indicator_key forKey:calculate_key];
            [dic_indicator_key release];
        }
        
        //訊號 dic_signal_key
        {
             NSMutableDictionary *dic_signal_key=[[NSMutableDictionary alloc] init];
            
            
            if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA1]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LFMESA1_BS];
               
               
                [dic_signal_key setObject:[NSNumber numberWithDouble:long_step_count] forKey:CL_his_data_signal_LFMESA1_State_add];
                
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LFMESA1_State];
                
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_LFMESA1_BS_Stop];
                
                //是否加碼訊號
                [dic_signal_key setObject:[NSNumber numberWithInt:Add_Long_Signal] forKey:CL_his_data_signal_LFMESA1_Add_Long];
               
                //是否超過歷史值的加碼訊號
                [dic_signal_key setObject:[NSNumber numberWithInt:Add_Long_Signal_ExcessMax] forKey:CL_his_data_signal_LFMESA1_Add_Long_ExcessMax];
                
                
                
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA2]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LFMESA2_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LFMESA2_State];
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_LFMESA2_BS_Stop];
                
                //是否加碼訊號
                [dic_signal_key setObject:[NSNumber numberWithInt:Add_Long_Signal] forKey:CL_his_data_signal_LFMESA2_Add_Long];
                
                //是否超過歷史值的加碼訊號
                [dic_signal_key setObject:[NSNumber numberWithInt:Add_Long_Signal_ExcessMax] forKey:CL_his_data_signal_LFMESA2_Add_Long_ExcessMax];
            }
            else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA3]) {
                [dic_signal_key setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LFMESA3_BS];
                [dic_signal_key setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LFMESA3_State];
                
                //停損機制
                [dic_signal_key setObject:[NSNumber numberWithDouble:BS_Stop] forKey:CL_his_data_signal_LFMESA3_BS_Stop];
                
                //是否加碼訊號
                [dic_signal_key setObject:[NSNumber numberWithInt:Add_Long_Signal] forKey:CL_his_data_signal_LFMESA3_Add_Long];
                
                //是否超過歷史值的加碼訊號
                [dic_signal_key setObject:[NSNumber numberWithInt:Add_Long_Signal_ExcessMax] forKey:CL_his_data_signal_LFMESA3_Add_Long_ExcessMax];
                
            }
            
            
            //添加
            [fdic_signal setObject:dic_signal_key forKey:calculate_key];
            [dic_signal_key release];
        }
        
        //損益 dic_profit_key （已經實現損益與未實現損益 存放所有的序列 至於其他的損益數據就採用暫存模式存放）
        {
             NSMutableDictionary *dic_profit_key=[[NSMutableDictionary alloc] init];            
            
            //最後一筆買賣尚未實現損益報酬率
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA1]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LFMESA1_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LFMESA1_shortratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_LFMESA1_longshortratio_lasttrade];
                    
                    
                    
                    
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA2]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LFMESA2_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LFMESA2_shortratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_LFMESA2_longshortratio_lasttrade];
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA3]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LFMESA3_longratio_lasttrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LFMESA3_shortratio_lasttrade];
                    
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:last_trade_long_profitratio+last_trade_short_profitratio] forKey:CL_his_data_profit_LFMESA3_longshortratio_lasttrade];
                }
            }
            //已經實現損益報酬率合計
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA1]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LFMESA1_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA1_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA1_longshortratio_realizedtrade];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA2]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LFMESA2_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA2_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA2_longshortratio_realizedtrade];
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA3]) {
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LFMESA3_longratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA3_shortratio_realizedtrade];
                    
                    [dic_profit_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum +realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA3_longshortratio_realizedtrade];
                    
                }
            }
            
            //添加
            [fdic_profit setObject:dic_profit_key forKey:calculate_key];
            [dic_profit_key release];
        }
        
        //temp dic_temp_key
        {
            
            NSMutableDictionary *dic_temp_key=[[NSMutableDictionary alloc] init];            
            //移動均線
            {
                [dic_temp_key setObject:[NSNumber numberWithDouble:ma_fast] forKey:HIS_dic_temp_MA_Fast];
                
                [dic_temp_key setObject:[NSNumber numberWithDouble:ma_slow] forKey:HIS_dic_temp_MA_Slow];
                
                [dic_temp_key setObject:[NSNumber numberWithBool:fastCrossSlow] forKey:HIS_dic_temp_MA_fastCrossSlow];
            } 
            
            //指標運算所需要使用
            {
                [dic_temp_key setObject:[NSNumber numberWithDouble:LFMESA_bout] forKey:HIS_dic_temp_LFMESA_bout];
                
                [dic_temp_key setObject:[NSNumber numberWithDouble:LFMESA_sout] forKey:HIS_dic_temp_LFMESA_sout];
                
                [dic_temp_key setObject:[NSNumber numberWithInt:LFMESA_b] forKey:HIS_dic_temp_LFMESA_b];
                
                [dic_temp_key setObject:[NSNumber numberWithInt:LFMESA_s] forKey:HIS_dic_temp_LFMESA_s];
                
                
                //摺疊次數
                [dic_temp_key setObject:[NSNumber numberWithInt:long_step_count] forKey:HIS_dic_temp_LFMESA_long_step_count];
                
                
                [dic_temp_key setObject:[NSNumber numberWithInt:long_step_count_no_limit] forKey:HIS_dic_temp_LFMESA_long_step_count_no_limit];
                
                [dic_temp_key setObject:[NSNumber numberWithInt:short_step_count] forKey:HIS_dic_temp_LFMESA_short_step_cpont];
                
                //歷史最大加碼次數
                [dic_temp_key setObject:[NSNumber numberWithInt:long_step_count_Max] forKey:HIS_dic_temp_LFMESA_long_step_Max];
                
                
                
                
                
            }
            
            //指標運算所需要使用mesa
            {
                [dic_temp_key setObject:[NSNumber numberWithDouble:price] forKey:HIS_dic_temp_price];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Smooth] forKey:HIS_dic_temp_Smooth];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Detrender] forKey:HIS_dic_temp_Detrender];
                [dic_temp_key setObject:[NSNumber numberWithDouble: Q1] forKey:HIS_dic_temp_Q1];
                [dic_temp_key setObject:[NSNumber numberWithDouble: l1] forKey:HIS_dic_temp_l1];
                [dic_temp_key setObject:[NSNumber numberWithDouble: jl] forKey:HIS_dic_temp_jl];
                [dic_temp_key setObject:[NSNumber numberWithDouble: jQ] forKey:HIS_dic_temp_jQ];
                [dic_temp_key setObject:[NSNumber numberWithDouble: l2] forKey:HIS_dic_temp_l2];
                [dic_temp_key setObject:[NSNumber numberWithDouble: Q2] forKey:HIS_dic_temp_Q2];
                [dic_temp_key setObject:[NSNumber numberWithDouble: Re] forKey:HIS_dic_temp_Re];
                [dic_temp_key setObject:[NSNumber numberWithDouble:lm] forKey:HIS_dic_temp_lm];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Period_Mesa] forKey:HIS_dic_temp_Period];
                [dic_temp_key setObject:[NSNumber numberWithDouble:SmoothPeriod] forKey:HIS_dic_temp_SmoothPeriod];
                [dic_temp_key setObject:[NSNumber numberWithDouble:Phase] forKey:HIS_dic_temp_Phase];
                [dic_temp_key setObject:[NSNumber numberWithDouble:DeltaPhase] forKey:HIS_dic_temp_DeltaPhase];
                
            }             
            
            //損益分析計算需要
            {
                //庫存部位買賣方向與數量
                [dic_temp_key setObject:[NSNumber numberWithInt:BS_last] forKey:HIS_dic_temp_profit_bs];
               
                //最後一筆進場價位
                [dic_temp_key setObject:[NSNumber numberWithDouble:enter_price] forKey:HIS_dic_temp_profit_enterprice];
                
                //平均進場價位
                [dic_temp_key setObject:[NSNumber numberWithDouble:enter_price_average] forKey:HIS_dic_temp_profit_enterprice_average];
                
                //是否有做多加碼
                [dic_temp_key setObject:[NSNumber numberWithBool:isAdd_long_step_count] forKey:HIS_dic_temp_profit_long_add];
                
                //是否有做空加碼
                [dic_temp_key setObject:[NSNumber numberWithBool:isAdd_short_step_count] forKey:HIS_dic_temp_profit_short_add];
                
                //單筆已經實現損益
                [dic_temp_key setObject:[NSNumber numberWithDouble:profit_single_realize] forKey:HIS_dic_temp_profit_single_realize];
                
                
                //單筆未實現損益
                [dic_temp_key setObject:[NSNumber numberWithDouble:profit_single_unrealize] forKey:HIS_dic_temp_profit_single_unrealize];
                
                
            }
            
            //損益分析結果最後一筆輸出
            {
                if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA1]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LFMESA1_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA1_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LFMESA1_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LFMESA1_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LFMESA1_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LFMESA1_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LFMESA1_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LFMESA1_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LFMESA1_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LFMESA1_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LFMESA1_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LFMESA1_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LFMESA1_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LFMESA1_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LFMESA1_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LFMESA1_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LFMESA1_LS_max_loss_temp];
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA1_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA1_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA1_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LFMESA1_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LFMESA1_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LFMESA1_LS_return_temp];
                    
                    
                }
                else if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA2]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LFMESA2_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA2_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LFMESA2_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LFMESA2_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LFMESA2_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LFMESA2_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LFMESA2_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LFMESA2_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LFMESA2_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LFMESA2_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LFMESA2_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LFMESA2_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LFMESA2_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LFMESA2_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LFMESA2_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LFMESA2_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LFMESA2_LS_max_loss_temp];
                    
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA2_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA2_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA2_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LFMESA2_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LFMESA2_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LFMESA2_LS_return_temp];
                    
                    
                }
                else   if ([calculate_key isEqualToString:Defaults_Calculate_LFMESA3]) {
                    
                    //做多已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LFMESA3_longratio_realizedtrade_temp];
                    //做空已經實現損益合計
                    [dic_temp_key setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LFMESA3_shortratio_realizedtrade_temp];
                    
                    
                    //做多總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LFMESA3_long_total_count_temp];
                    //做多賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LFMESA3_long_win_count_temp];
                    //做多勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LFMESA3_long_win_ratio_temp];
                    
                    
                    //做空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LFMESA3_short_total_count_temp];
                    //做空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LFMESA3_short_win_count_temp];
                    //做空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LFMESA3_short_win_ratio_temp];
                    
                    
                    
                    //多空總交易次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LFMESA3_LS_total_count_temp];
                    //多空賺錢次數
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LFMESA3_LS_win_count_temp];
                    //多空勝率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LFMESA3_LS_win_ratio_temp];
                    
                    //做多最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LFMESA3_long_max_gain_temp];
                    
                    
                    
                    //做多最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LFMESA3_long_max_loss_temp];
                    
                    //做空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LFMESA3_short_max_gain_temp];
                    
                    //做空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LFMESA3_short_max_loss_temp];
                    
                    //多空最大獲利率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LFMESA3_LS_max_gain_temp  ];
                    
                    //多空最大虧損率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LFMESA3_LS_max_loss_temp];
                    
                    //作多年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA3_long_period_temp];
                    //作空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA3_short_period_temp];
                    //多空年間
                    [dic_temp_key setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LFMESA3_LS_period_temp];
                    
                    
                    //作多年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LFMESA3_long_return_temp];
                    //作空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LFMESA3_short_return_temp];
                    //多空年化報酬率
                    [dic_temp_key setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LFMESA3_LS_return_temp];
                    
                }
                
                
            }
            
            //添加
            [fdic_temp setObject:dic_temp_key forKey:calculate_key];
            [dic_temp_key release];
            
        }
        
    }
    
    
}

//傳回temp的資料 float
-(float)get_his_temp_value:(NSString *)key calculate_key:(NSString *)calculate_key i:(int)i historyData:(NSMutableArray *)ffhisData  {
    
    if (i>=0) {
        NSMutableDictionary *hisdata_temp_dic=[[[ffhisData objectAtIndex:i] objectForKey:HIS_dic_temp] objectForKey:calculate_key];
        
        if ([hisdata_temp_dic objectForKey:key]) {
            return [[hisdata_temp_dic objectForKey:key] doubleValue];
        }
        else {
            return 0;
        }
        
        
        
    }
    else {
        return 0; 
    }
       
    
}

//傳回temp的資料 float
-(NSNumber *)get_his_temp_NSNumber:(NSString *)key calculate_key:(NSString *)calculate_key i:(int)i historyData:(NSMutableArray *)ffhisData  {
    
    if (i>=0) {
        NSMutableDictionary *hisdata_temp_dic=[[[ffhisData objectAtIndex:i] objectForKey:HIS_dic_temp] objectForKey:calculate_key];
        
        if ([hisdata_temp_dic objectForKey:key]) {
            return  [hisdata_temp_dic objectForKey:key]  ;
        }
        else {
            return nil;
        }
        
        
        
    }
    else {
        return nil;
    }
    
    
}



//傳回最佳化temp的資料value
-(float)get_his_temp_optimize_value:(NSString *)key  i:(int)i historyData:(NSMutableArray *)ffhisData  {
    
    if (i>=0 && i<[ffhisData count]) {
       
        NSMutableDictionary *hisdata_temp_dic= [[ffhisData objectAtIndex:i]  objectForKey:HIS_optimize_temp];
        //NSLog(@"HIS_optimize_temp=%@",hisdata_temp_dic);
        
        
        
        if ([hisdata_temp_dic objectForKey:key]) {
            return [[hisdata_temp_dic objectForKey:key] doubleValue];
        }
        else {
            return 0;
        }
        
        
        
    }
    else {
        return 0;
    }
    
    
}
//傳回最佳化temp的資料value
-(NSNumber *)get_his_temp_optimize_NSNumber:(NSString *)key  i:(int)i historyData:(NSMutableArray *)ffhisData  {
    
    if (i>=0 && i<[ffhisData count]) {
        
        NSMutableDictionary *hisdata_temp_dic= [[ffhisData objectAtIndex:i]  objectForKey:HIS_optimize_temp];
        //NSLog(@"HIS_optimize_temp=%@",hisdata_temp_dic);
        
        
        
        if ([hisdata_temp_dic objectForKey:key]) {
            return  [hisdata_temp_dic objectForKey:key] ;
        }
        else {
            return nil;
        }
        
        
        
    }
    else {
        return nil;
    }
    
    
}


 

#pragma mark -
#pragma mark 歷史資料序列取出某一筆某一代號資料

//取出
-(id)get_his_data_serial_forkey:(NSString *)key index_before:(int)index_before HIS_dic_key:(NSString *)   HIS_dic_key{
    
    NSMutableArray *his_data_serial_temp;
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_plist  ]) {
        //方法：硬碟:plist
        his_data_serial_temp= [NSMutableArray arrayWithContentsOfFile:Path_history_serial_write_to_catch_plist]  ;
        
    }
    else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_arch  ]){
        //方法：硬碟:arch
        his_data_serial_temp=    [NSKeyedUnarchiver unarchiveObjectWithFile:Path_history_serial_write_to_catch_arch] ;
        
        
    }
    else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_Memory  ]){
        //方法：記憶體
        his_data_serial_temp=  his_data_serial  ;
        
    }
    else {
        his_data_serial_temp= nil;
    }
    
    int last_index;
    if ([his_data_serial_temp count] - index_before >0) {
        
        last_index=[his_data_serial_temp count]- index_before-1;
        
    }
    else {
        
        last_index=0;
    }
    
    NSString *calculateMethod=[[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_method];
    
    NSString *calculateFiled=[[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_filed];
    
    if ([[[[his_data_serial_temp objectAtIndex:last_index] objectForKey:HIS_dic_key] objectForKey:calculateMethod] objectForKey:calculateFiled]) {
        
        return [[[his_data_serial_temp objectAtIndex:last_index] objectForKey:HIS_dic_key] objectForKey:calculateFiled];
    }
    else {
        return nil;
    }
    
    
    
    
}
 
#pragma mark -
#pragma mark 歷史資料序列取出最後一筆某一代號資料
-(id)get_last_his_data_serial_forkey:(NSString *)key HIS_dic_key:(NSString *) HIS_dic_key index_before:(int)index_before{
    
     
    
    NSMutableArray *his_data_serial_temp;
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_plist  ]) {
        //方法：硬碟:plist
        his_data_serial_temp= [NSMutableArray arrayWithContentsOfFile:Path_history_serial_write_to_catch_plist]  ;
        
    }
    else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_arch  ]){
        //方法：硬碟:arch
        his_data_serial_temp=    [NSKeyedUnarchiver unarchiveObjectWithFile:Path_history_serial_write_to_catch_arch] ;
        
        
    }
    else if ([[prefs objectForKey:Defaults_History_Serial_Method] isEqualToString:Defaults_History_Serial_Method_Memory  ]){
        //方法：記憶體
        his_data_serial_temp=  his_data_serial  ;
        
    }
    else {
        his_data_serial_temp= nil;
        
    }
    
   
    
    
    int last_index;
    last_index=[his_data_serial_temp count]- index_before-1;    
    
    if (last_index < 0) {
        last_index=0;
    }
    //NSLog(@"count=%ld index_before=%i last_index=%i ",[his_data_serial_temp count],index_before,last_index);
    
    NSString *calculateMethod=[[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_method];
    
    NSString *calculateField=[[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_filed];
     
    
    return [[[[his_data_serial_temp objectAtIndex:last_index] objectForKey:HIS_dic_key] objectForKey:calculateMethod] objectForKey:calculateField];
}

 -(id)get_last_his_data_serial_forkey:(NSString *)key HIS_dic_key:(NSString *) HIS_dic_key{
    
    
     
     
     //NSLog(@"ccc=%@", [[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_method]);
    
    NSString *calculateMethod=[[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_method];
    
    NSString *calculateField=[[[delgete_m table_column_object_array] object_table_column_array_from_column_identfiler:key] objectForKey:Table_Column_hisdata_calculate_filed];
    
    NSMutableDictionary *tempdic;
    
    //功能步驟：個股時間序列上新增資料集合步驟 功能步驟: 1    
    if ([HIS_dic_key isEqualToString:HIS_dic_signal]) {
        tempdic=last_dic_signal;
    }
    else if ([HIS_dic_key isEqualToString:HIS_dic_indicator]) {
         tempdic=last_dic_indicator;
    }
    else if ([HIS_dic_key isEqualToString:HIS_dic_profit]) {
         tempdic=last_dic_profit;
    }
    else if ([HIS_dic_key isEqualToString:HIS_dic_temp]) {
         tempdic=last_dic_temp;
    }
    else{
        tempdic=nil;
    }
    
    
    if (tempdic) {
        //表示有最後一筆訊號暫存資料
        if ( [[tempdic objectForKey:calculateMethod]  objectForKey:calculateField]) {
            
            return  [[tempdic objectForKey:calculateMethod]  objectForKey:calculateField];
        }
        else {
            
            return nil;
        }
        
    }
    else {
        
        //表示無 最後一筆訊號暫存資料 從整個序列取出
       // return   [self get_his_data_serial_profit_forkey: key index_before:0];
        return   [self get_his_data_serial_forkey: key index_before:0 HIS_dic_key:HIS_dic_key ];        
    }
    
    
    
    
}

#pragma mark -
#pragma mark 歷史資料序列取出某一欄位的所有資料
-(id)get_single_column_all_his_data:(NSMutableDictionary *)columndata{

    NSMutableArray *out_array=[[[NSMutableArray alloc] init] autorelease];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd";
    {
        NSString *locationpath= [columndata objectForKey:Table_Column_data_loactaionPath] ;
        
        //路徑下1層
        NSString *locationpath1;
        if ([locationpath isEqualToString:loactaionPath_tableobject_data_array_object_his_data_serial_signal]) {
            
            locationpath1=HIS_dic_signal;
            
            
        }
        else if ([locationpath isEqualToString:loactaionPath_tableobject_data_array_object_his_data_serial_indicator]) {
            locationpath1=HIS_dic_indicator;
            
        }
        else if ([locationpath isEqualToString:loactaionPath_tableobject_data_array_object_his_data_serial_profit]) {
            locationpath1=HIS_dic_profit;
            
        }
        else if ([locationpath isEqualToString:loactaionPath_tableobject_data_array_object_his_data_serial_temp]) {
            locationpath1=HIS_dic_temp;
            
            
        }
        else{
            locationpath1=nil;
        }
        
        //路徑下2層
        NSString *locationpath2=[columndata objectForKey:Table_Column_hisdata_calculate_method];
        
        //路徑下3層
        NSString *locationpath3=[columndata objectForKey:Table_Column_hisdata_calculate_filed];
        
        //製作輸出資料陣列
                
        for (NSMutableDictionary *dic in [self get_his_data_serial]) {
            
            //NSLog(@"date=%@ %@", [dic objectForKey:HIS_basic_date], [[(NSMutableDictionary *)[dic objectForKey:locationpath1] objectForKey:locationpath2] objectForKey:locationpath3] );
            
            if ([[(NSMutableDictionary *)[dic objectForKey:locationpath1] objectForKey:locationpath2] objectForKey:locationpath3]   ) {
                
                if ([dic objectForKey:HIS_basic_date]) {
                    NSMutableDictionary *dic_single=[[NSMutableDictionary alloc] init];
                    //加入資料
                    {
                        //1.原始日期
                        [dic_single setObject:[dic objectForKey:HIS_basic_date] forKey:HIS_basic_date];
                        
                        //2.轉換日期格式
                        {                             
                            //NSTimeZone *gmt = [NSTimeZone timeZoneWithName: [[self table_data] objectForKey:DB_object_sqlite_basic_timezone] ];
                            
                            NSTimeZone *gmt = [NSTimeZone timeZoneForSecondsFromGMT:0] ;
                            
                            [dateFormatter setTimeZone:gmt];
                            
                                                       
                            
                            
                            NSString *timeStamp = [dateFormatter stringFromDate:[dic objectForKey:HIS_basic_date]];
                            
                            [dic_single setObject:timeStamp forKey:TransFormDate];                             
                            
                        }
                        
                       
                   
                        
                        //3.一日內所有的的資料 很重要
                        [dic_single setObject:dic forKey:Single_all_dic];
                        
                    
                    }
                    
                    [out_array addObject:dic_single];
                    [dic_single release];
                    
                }
                
                
                
            }
            
        }
    
    }
    [dateFormatter release];
    
    return out_array;
}


#pragma mark -
#pragma mark 物件消滅
-(void)dealloc{
    
  
   
    
    [table_data release];
    
    [data_object_para  release];
    
    [last_dic_indicator release]; //指標數值
    [last_dic_signal release];    //訊號數值
    [last_dic_profit release];    //訊號數值
    [last_dic_temp release];      //暫存檔    
    
    [Path_history_serial_write_to_catch_arch release]; 
    [Path_history_serial_write_to_catch_plist release];    
   
    [his_data_serial release];
    [his_data_high release];
    [his_data_low release];
    
    [super dealloc];
  
}



#pragma mark -
#pragma mark 進行最佳化

-(void)run_optimize:(NSString *)optimize_method{
    
    //先取出是否要用調整收盤價當作收盤價
    {
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        isUseAdjClose=[[prefs objectForKey:Defaults_isUse_AdjClose] boolValue];
        
    }
    
    NSString *code=[table_data objectForKey:DB_object_sqlite_basic_code];
     
    NSLog(@"進行最佳化 mehod=%@ code=%@",optimize_method,code);
    
    //取出最佳化資料字典
    NSMutableDictionary *para_dic;
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *para_dic_par=[prefs  objectForKey:Para_Optimize_Dic];
    {
        para_dic=[para_dic_par  objectForKey:optimize_method];
        // NSLog(@"最佳化參數字典=%@",para_dic);
                       
    }
    
    //針對不同最佳化方法開始最佳化
    if ([optimize_method isEqualToString:Para_Optimize_calculates_array_MESA]) {
        
        [self optimize_MESA:para_dic];
               
    }
    else if ([optimize_method isEqualToString:Para_Optimize_calculates_array_LF]){
      
        
         [self optimize_LF:para_dic];
    }
    else if ([optimize_method isEqualToString:Para_Optimize_calculates_array_LFMESA]){
        
       
        [self optimize_LFMESA:para_dic];
    }
    
    
}
 
-(void)optimize_MESA:(NSMutableDictionary *)para_dic{
    
    
    NSLog(@"最佳化：mesa=%@",[table_data objectForKey:DB_object_sqlite_basic_code]);
    
    //1.取出日期區間
    NSDate *start;
    NSDate *end;
    {
        
        start=[para_dic objectForKey:Para_Optimize_date_start];
        end= [para_dic objectForKey:Para_Optimize_date_end];
        
        
        NSLog(@"開始=%@", start);
        NSLog(@"結束=%@", end );
    }
    
    //2.取出歷史資料
    NSMutableArray *his_dic_serial=[self get_his_data_serial];
    
    if (his_dic_serial) {
        
        //1.參數
        float FastLim_start,SlowLim_start;
        float FastLim_end,SlowLim_end;
        float FastLim_step,SlowLim_step;
        
        float long_cost,short_cost;//買進與賣出交易成本
        
        
        float Stop_ratio;           //停損率
        int isUse_Stop;             //是否停損
        
        
        int compare_method;
        {
            //技術指標循環參數
            SlowLim_start= [[para_dic objectForKey:Para_Default_start_1] floatValue];
            SlowLim_end= [[para_dic objectForKey:Para_Default_end_1] floatValue];
            SlowLim_step= [[para_dic objectForKey:Para_Default_step_1] floatValue];
            
            
            FastLim_start= [[para_dic objectForKey:Para_Default_start_2] floatValue];
            FastLim_end= [[para_dic objectForKey:Para_Default_end_2] floatValue];
            FastLim_step= [[para_dic objectForKey:Para_Default_step_2] floatValue];
            
            //比較準則
            compare_method= [[para_dic objectForKey:Para_Optimize_compare_method] intValue];
            
            
            long_cost= [[para_dic objectForKey:Para_Optimize_long_cost] floatValue];
            short_cost= [[para_dic objectForKey:Para_Optimize_short_cost] floatValue];
            
            //停損機制
            isUse_Stop= [[para_dic objectForKey:Para_Optimize_isUse_Stop] intValue];
            Stop_ratio= [[para_dic objectForKey:Para_Optimize_Stop_ratio] floatValue];
        }
        
        
        //2.進入參數循環
        NSMutableArray *optimize_data_dic=[[NSMutableArray alloc]init]; //儲存每筆計算結果資料
        int count_loop=0; //計數器
        for (double SlowLim=SlowLim_start; SlowLim<=SlowLim_end; SlowLim=SlowLim+SlowLim_step ) {
            
            for (double FastLim=FastLim_start; FastLim<=FastLim_end; FastLim=FastLim+FastLim_step ) {
                
                
                NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                
                count_loop++;
                
                //宣告損益計算變數
                
                double last_trade_long_profitratio;         //最後一筆做多獲利率
                double last_trade_short_profitratio;        //最後一筆做空獲利率
                
                
                double realized_trade_long_profitratio;     //已經實現做多損益
                double realized_trade_short_profitratio;    //已經實現做空損益
                double realized_trade_long_profitratio_sum; //已經實現做多損益合計
                double realized_trade_short_profitratio_sum;//已經實現做空損益合計
                
                double long_total_count; //做多交易次數
                double long_win_count;   //做多交易賺錢次數
                double long_win_ratio;   //做多勝率
                
                double short_total_count; //做空交易次數
                double short_win_count;   //做空交易賺錢次數
                double short_win_ratio;   //做空勝率
                
                double ls_total_count; //多空交易次數
                double ls_win_count;   //多空交易賺錢次數
                double ls_win_ratio;   //多空勝率
                
                double long_max_gain; //做多最大獲利率
                double long_max_loss; //做多最大虧損率
                double short_max_gain; //做空最大獲利率
                double short_max_loss; //做空最大虧損率
                double ls_max_gain;  //多空最大獲利率
                double ls_max_loss; //多空最大虧損率
                
                double year; //開始計算日期
                
                double return_long;// 作多年化報酬率
                double return_short;// 作空年化報酬率
                double return_ls;// 作空年化報酬率
                {
                    
                    last_trade_long_profitratio=0;
                    last_trade_short_profitratio=0;
                    
                    
                    realized_trade_long_profitratio_sum=0;
                    realized_trade_short_profitratio_sum=0;
                    
                    long_total_count=0;
                    long_win_count=0;
                    long_win_ratio=0;
                    
                    short_total_count=0;
                    short_win_count=0;
                    short_win_ratio=0;
                    
                    ls_total_count=0;
                    ls_win_count=0;
                    ls_win_ratio=0;
                    
                    long_max_gain=0; //做多最大獲利率
                    long_max_loss=0; //做多最大虧損率
                    short_max_gain=0; //做空最大獲利率
                    short_max_loss=0; //做空最大虧損率
                    ls_max_gain=0;  //多空最大獲利率
                    ls_max_loss=0; //多空最大虧損率
                    
                    year=0;
                    
                    return_long=0;
                    return_short=0;
                    return_ls=0;
                    
                }
                
                //a.進入每筆最佳化計算
                for (int i=0 ; i<[his_dic_serial count]; i++) {
                    
                    
                    NSMutableDictionary *his_dic =[his_data_serial objectAtIndex:i];
                    
                    NSDate *now=[his_dic objectForKey:HIS_basic_date];
                    
                    
                    //判斷區間內
                    if ([now compare:start]==NSOrderedDescending  && [now compare:end]==NSOrderedAscending) {
                        
                        //正式進入計算
                        
                        //建立 計算暫存記憶體空間
                        NSMutableDictionary *temp_cal=[[NSMutableDictionary alloc] init];
                        
                        [his_dic setObject:temp_cal forKey:HIS_optimize_temp];
                        
                        [temp_cal release];
                        
                        //開始計算
                        {
                            
                            //1.開高收低 基本每筆資料
                            double  high,low,open  ;
                            double  close;
                            {
                                //調整收盤價比率
                                double adj_ratio;
                                {
                                    double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
                                    double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                                    
                                    
                                    if (isUseAdjClose==YES) {
                                        adj_ratio=adj_close/close;
                                    }
                                    else{
                                        adj_ratio=1;
                                    }
                                }
                                
                                
                                
                                
                                high=[[his_dic objectForKey:HIS_basic_high] doubleValue]* adj_ratio;
                                low=[[his_dic objectForKey:HIS_basic_low] doubleValue]* adj_ratio;
                                open=[[his_dic objectForKey:HIS_basic_open] doubleValue]* adj_ratio;
                                close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
                                
                            }
                            
                            //2.計算用的變數
                            double Smooth,price,Detrender,Period,Q1,l1,jl,jQ,l2,Q2,Re,lm,SmoothPeriod,Phase,DeltaPhase,alpha,MAMA,FAMA;
                            
                            //3.計算MESA
                            {
                                price =(high +low)/2;
                                
                                
                                Smooth =(4 * price + 3 *[self get_his_temp_optimize_value:HIS_dic_temp_price  i:i-1 historyData:his_dic_serial]  + 2 * [self get_his_temp_optimize_value:HIS_dic_temp_price  i:i-2 historyData:his_dic_serial] + [self get_his_temp_optimize_value:HIS_dic_temp_price  i:i-3 historyData:his_dic_serial])/10;
                                
                                Detrender=(0.0962*Smooth+0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-2 historyData:his_dic_serial] -0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-4 historyData:his_dic_serial]-0.0962*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54);
                                
                                Q1 =(0.0962*Detrender +0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-2 historyData:his_dic_serial]-0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-4 historyData:his_dic_serial]-0.0962*[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54);
                                
                                l1 =[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-3 historyData:his_dic_serial];
                                jl=(0.0962*l1+0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_l1  i:i-2 historyData:his_dic_serial]-0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_l1  i:i-4 historyData:his_dic_serial]-.0962*[self get_his_temp_optimize_value:HIS_dic_temp_l1  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54);
                                
                                jQ=(0.0962*Q1+.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Q1  i:i-2 historyData:his_dic_serial]-.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Q1  i:i-4 historyData:his_dic_serial]-0.0962*[self get_his_temp_optimize_value:HIS_dic_temp_Q1  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54) ;
                                
                                l2=l1-jQ;
                                Q2=Q1+jl;
                                
                                l2=0.2*l2 +0.8*[self get_his_temp_optimize_value:HIS_dic_temp_l2  i:i-1 historyData:his_dic_serial];
                                Q2=0.2*Q2+0.8*[self get_his_temp_optimize_value:HIS_dic_temp_Q2  i:i-1 historyData:his_dic_serial];
                                
                                Re =l2 *[self get_his_temp_optimize_value:HIS_dic_temp_l2  i:i-1 historyData:his_dic_serial]+Q2*[self get_his_temp_optimize_value:HIS_dic_temp_Q2  i:i-1 historyData:his_dic_serial];
                                lm=l2*[self get_his_temp_optimize_value:HIS_dic_temp_Q2  i:i-1 historyData:his_dic_serial]-Q2*[self get_his_temp_optimize_value:HIS_dic_temp_l2  i:i-1 historyData:his_dic_serial];
                                
                                Re =0.2*Re +0.8*[self get_his_temp_optimize_value:HIS_dic_temp_Re  i:i-1 historyData:his_dic_serial];
                                lm=0.2*lm+0.8*[self get_his_temp_optimize_value:HIS_dic_temp_lm  i:i-1 historyData:his_dic_serial];
                                
                                
                                if( lm  !=0 && Re !=0 )
                                {
                                    Period = 360/(atan((lm /Re ))*180/(4*atan(1)));
                                    
                                }
                                else {
                                    Period=0;
                                }
                                if( Period >1.5*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial])
                                    Period =1.5*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial];
                                
                                if(Period <0.67*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial])
                                    Period =0.67*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial];
                                
                                
                                if(Period <6)
                                    Period =6;
                                if(Period >50)
                                    Period =50;
                                
                                Period =0.2*Period +0.8*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial];
                                
                                
                                SmoothPeriod =0.33*Period +0.67*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-1 historyData:his_dic_serial];
                                
                                if( l1  !=0 ){
                                    Phase =atan(Q1 /l1 )*180/(4*atan(1));
                                }
                                else{
                                    Phase=0;
                                }
                                
                                DeltaPhase=[self get_his_temp_optimize_value:HIS_dic_temp_Phase  i:i-1 historyData:his_dic_serial] - Phase ;
                                
                                if(DeltaPhase <1)
                                    DeltaPhase =1;
                                alpha =FastLim/DeltaPhase ;
                                
                                if(alpha <SlowLim)
                                    alpha  =SlowLim;
                                
                                if( alpha >FastLim)
                                    alpha =FastLim;
                                
                                MAMA =alpha *price +(1-alpha )*[self get_his_temp_optimize_value:HIS_dic_temp_MAMA  i:i-1 historyData:his_dic_serial];
                                FAMA =0.5*alpha*MAMA+(1-0.5*alpha)*[self get_his_temp_optimize_value:HIS_dic_temp_FAMA  i:i-1 historyData:his_dic_serial];
                            }
                            
                            //4.訊號判斷
                            int BuyOrSell;      //此位置 i 是否要買或賣
                            int Position_State; //此位置 i 多空狀態
                            int BS_Stop; //停損機制 2表示做空停損 -2表示做多停損
                            BS_Stop=0;
                            double  FAMA_1, MAMA_1;
                            {
                                BuyOrSell=0;
                                Position_State=0;
                                
                                
                                if (i>0) {
                                    
                                    FAMA_1= [self get_his_temp_optimize_value:HIS_dic_temp_FAMA  i:i-1 historyData:his_dic_serial] ;
                                    
                                    MAMA_1=[self get_his_temp_optimize_value:HIS_dic_temp_MAMA  i:i-1 historyData:his_dic_serial] ;
                                    
                                    
                                    
                                    //買賣訊號
                                    if (FAMA>MAMA && FAMA_1<MAMA_1) {
                                        BuyOrSell=-1;
                                        
                                    }
                                    else if (FAMA<MAMA && FAMA_1>MAMA_1) {
                                        BuyOrSell=1;
                                    }
                                    else {
                                        BuyOrSell=0;
                                    }
                                    
                                    //狀態
                                    if (FAMA>MAMA) {
                                        Position_State=-1;
                                    }
                                    else {
                                        Position_State=1;
                                    }
                                    
                                    
                                }
                                
                                
                            }
                            
                            
                            //6.損益部位
                            
                            
                            int BS_last ;// 最後一期買賣方向 因為是以隔天開盤價作為當期買賣價位
                            double enter_price; //最後一期買進場價位
                            {
                                //變數歸0
                                {
                                    last_trade_long_profitratio=0;
                                    last_trade_short_profitratio=0;
                                    
                                    realized_trade_long_profitratio=0;
                                    realized_trade_short_profitratio=0;
                                    
                                    realized_trade_long_profitratio_sum=0;
                                    realized_trade_short_profitratio_sum=0;
                                    
                                    long_total_count=0;
                                    long_win_count=0;
                                    long_win_ratio=0;
                                    
                                    short_total_count=0;
                                    short_win_count=0;
                                    short_win_ratio=0;
                                    
                                    ls_total_count=0;
                                    ls_win_count=0;
                                    ls_win_ratio=0;
                                    
                                    long_max_gain=0; //做多最大獲利率
                                    long_max_loss=0; //做多最大虧損率
                                    short_max_gain=0; //做空最大獲利率
                                    short_max_loss=0; //做空最大虧損率
                                    ls_max_gain=0;  //多空最大獲利率
                                    ls_max_loss=0; //多空最大虧損率
                                    
                                    
                                    BS_last=0;
                                    enter_price=0;
                                    year=0;
                                    
                                    return_long=0;
                                    return_short=0;
                                    return_ls=0;
                                }
                                
                                if (i>0) {
                                    
                                    
                                    int BS_1 ;// 前一期買賣動作方向 因為是以隔天開盤價作為當期買賣價位
                                    
                                    //停損機制 最佳化
                                    int BS_Stop_1; //前一期是否有出現停損動作
                                    //BS_Stop_1=0;
                                    
                                    //1.取出前一期的資料
                                    NSMutableDictionary *his_dic_1=[his_data_serial objectAtIndex:i-1];//前一筆
                                    NSMutableDictionary *his_dic_0=[his_data_serial objectAtIndex:0];  //第0筆
                                    
                                    
                                    {
                                        
                                        //停損機制 最佳化
                                        //前一期是否有出現停損動作
                                        BS_Stop_1=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_signal_MESA_BS_Stop] intValue];
                                        
                                        
                                        //前一期 買賣動作方向
                                        BS_1=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_signal_MESA_BS] intValue];
                                        
                                        
                                        
                                        //前一期 已經實現做多合計
                                        realized_trade_long_profitratio_sum=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_longratio_realizedtrade_temp] doubleValue];
                                        
                                        
                                        
                                        //前一期 已經實現做空合計
                                        realized_trade_short_profitratio_sum=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_shortratio_realizedtrade_temp] doubleValue];
                                        
                                        //前一期 做多交易次數
                                        long_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_long_total_count_temp] doubleValue];
                                        
                                        //前一期 做多賺錢交易次數
                                        long_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_long_win_count_temp] doubleValue];
                                        
                                        //前一期 做多勝率
                                        long_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_long_win_ratio_temp] doubleValue];
                                        
                                        
                                        //前一期 做空交易次數
                                        short_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_short_total_count_temp] doubleValue];
                                        
                                        //前一期 做空賺錢交易次數
                                        short_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_short_win_count_temp] doubleValue];
                                        
                                        //前一期 做空勝率
                                        short_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_short_win_ratio_temp] doubleValue];
                                        
                                        
                                        //前一期 多空交易次數
                                        ls_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_LS_total_count_temp] doubleValue];
                                        
                                        //前一期 多空賺錢交易次數
                                        ls_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_LS_win_count_temp] doubleValue];
                                        
                                        //前一期 多空勝率
                                        ls_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_LS_win_ratio_temp] doubleValue];
                                        
                                        //做多最大獲利率
                                        long_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_long_max_gain_temp] doubleValue];
                                        
                                        //做多最大虧損率
                                        long_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_long_max_loss_temp] doubleValue];
                                        
                                        //做空最大獲利率
                                        short_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_short_max_gain_temp] doubleValue];
                                        
                                        //做空最大虧損率
                                        short_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_short_max_loss_temp] doubleValue];
                                        
                                        //多空最大獲利率
                                        ls_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_LS_max_gain_temp] doubleValue];
                                        
                                        //多空最大虧損率
                                        ls_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_MESA_LS_max_loss_temp] doubleValue];
                                        
                                        
                                        
                                        
                                    }
                                    
                                    
                                    //2.判斷上一期是否有買賣動作
                                    if (BS_1==0) {
                                        
                                        enter_price=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice  i:i-1 historyData:his_dic_serial] ;
                                        
                                        
                                        //停損機制 最佳化
                                        //前一期是否需要停損
                                        if (BS_Stop_1==-2 ) {
                                            
                                            //NSLog(@"BS_Stop_1==-2");
                                            
                                            //前一期出現需要做多停損訊號
                                            BS_last=0;
                                            //作多出場損益
                                            {
                                                //做多最近一筆 含有交易成本
                                                realized_trade_long_profitratio=(open-enter_price)/enter_price*100-(long_cost+short_cost)*100;
                                                
                                                
                                                
                                                //累計做多
                                                realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                                                
                                                //累計做多交易次數
                                                long_total_count=long_total_count+1;
                                                
                                                //做多交易賺錢次數
                                                if (realized_trade_long_profitratio>0) {
                                                    //賺錢才可以+1
                                                    long_win_count=long_win_count+1;
                                                }
                                                else{
                                                    long_win_count=long_win_count;
                                                }
                                                
                                                //勝率
                                                if (long_total_count>0) {
                                                    long_win_ratio= long_win_count/long_total_count*100;
                                                }
                                                else{
                                                    long_win_ratio=0;
                                                }
                                                
                                                //做多最大獲利
                                                if (realized_trade_long_profitratio>long_max_gain) {
                                                    long_max_gain=realized_trade_long_profitratio;
                                                }
                                                
                                                //做多最大損失
                                                if (realized_trade_long_profitratio<long_max_loss) {
                                                    long_max_loss=realized_trade_long_profitratio;
                                                }
                                                
                                                
                                            }
                                            
                                        }
                                        else if (BS_Stop_1==2 ){
                                            //前一期出現做空需要停損的訊號
                                            BS_last=0;
                                            //作空出場損益
                                            {
                                                //做空最近一筆 含有交易成本
                                                realized_trade_short_profitratio=(enter_price-open)/enter_price*100-(long_cost+short_cost)*100;
                                                
                                                //累計做多
                                                realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                                                
                                                
                                                //累計做空交易次數
                                                short_total_count=short_total_count+1;
                                                
                                                
                                                //做空交易賺錢次數
                                                if (realized_trade_short_profitratio>0) {
                                                    //賺錢才可以+1
                                                    short_win_count=short_win_count+1;
                                                }
                                                else{
                                                    short_win_count=short_win_count;
                                                }
                                                
                                                //勝率
                                                if (short_total_count>0) {
                                                    short_win_ratio= short_win_count/short_total_count*100;
                                                }
                                                else{
                                                    short_win_ratio=0;
                                                }
                                                
                                                
                                                //做空最大獲利
                                                if (realized_trade_short_profitratio>short_max_gain) {
                                                    short_max_gain=realized_trade_short_profitratio;
                                                }
                                                
                                                //做空最大損失
                                                if (realized_trade_short_profitratio<short_max_loss) {
                                                    short_max_loss=realized_trade_short_profitratio;
                                                }
                                            }
                                            
                                        }
                                        else{
                                            /*
                                             if (enter_price==0) {
                                             NSLog(@"slow=%f fast=%f",SlowLim,FastLim);
                                             }
                                             */
                                            
                                            //表示上一期無買賣動作
                                            
                                            //取出最後一筆的狀態 在轉移到下一期
                                            BS_last=[self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial] ;
                                            
                                        }
                                        
                                        
                                    }
                                    else{
                                        //表示上一期有買賣動作
                                        
                                        //1.計算已經實現損益
                                        {
                                            //上一期尚未動作之前的部位
                                            int BS_last_unchange;        //上一期的部位方向
                                            double enterprice_last_unchange;//上一期的部位的進場價格還尚未更新到本期的開盤價之前的資料
                                            
                                            BS_last_unchange=[self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial];
                                            enterprice_last_unchange=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice  i:i-1 historyData:his_dic_serial];
                                            
                                            
                                            //計算已經實現損益與累計實現損益
                                            if (BS_last_unchange==1) {
                                                
                                                //做多最近一筆 含有交易成本
                                                realized_trade_long_profitratio=(open-enterprice_last_unchange)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                                                
                                                //累計做多
                                                realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                                                
                                                //累計做多交易次數
                                                long_total_count=long_total_count+1;
                                                
                                                //做多交易賺錢次數
                                                if (realized_trade_long_profitratio>0) {
                                                    //賺錢才可以+1
                                                    long_win_count=long_win_count+1;
                                                }
                                                else{
                                                    long_win_count=long_win_count;
                                                }
                                                
                                                //勝率
                                                if (long_total_count>0) {
                                                    long_win_ratio= long_win_count/long_total_count*100;
                                                }
                                                else{
                                                    long_win_ratio=0;
                                                }
                                                
                                                //做多最大獲利
                                                if (realized_trade_long_profitratio>long_max_gain) {
                                                    long_max_gain=realized_trade_long_profitratio;
                                                }
                                                
                                                //做多最大損失
                                                if (realized_trade_long_profitratio<long_max_loss) {
                                                    long_max_loss=realized_trade_long_profitratio;
                                                }
                                                
                                                
                                            }
                                            else if (BS_last_unchange==-1){
                                                //做空最近一筆 含有交易成本
                                                realized_trade_short_profitratio=(enterprice_last_unchange-open)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                                                
                                                //累計做多
                                                realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                                                
                                                
                                                //累計做空交易次數
                                                short_total_count=short_total_count+1;
                                                
                                                
                                                //做空交易賺錢次數
                                                if (realized_trade_short_profitratio>0) {
                                                    //賺錢才可以+1
                                                    short_win_count=short_win_count+1;
                                                }
                                                else{
                                                    short_win_count=short_win_count;
                                                }
                                                
                                                //勝率
                                                if (short_total_count>0) {
                                                    short_win_ratio= short_win_count/short_total_count*100;
                                                }
                                                else{
                                                    short_win_ratio=0;
                                                }
                                                
                                                
                                                //做空最大獲利
                                                if (realized_trade_short_profitratio>short_max_gain) {
                                                    short_max_gain=realized_trade_short_profitratio;
                                                }
                                                
                                                //做空最大損失
                                                if (realized_trade_short_profitratio<short_max_loss) {
                                                    short_max_loss=realized_trade_short_profitratio;
                                                }
                                                
                                                
                                                
                                            }
                                            
                                            //多空合計
                                            ls_total_count=long_total_count+short_total_count;
                                            ls_win_count=long_win_count+short_win_count;
                                            
                                            if (ls_total_count>0) {
                                                ls_win_ratio=ls_win_count/ls_total_count*100;
                                            }
                                            else{
                                                ls_win_ratio=0;
                                            }
                                            
                                            //多空最大獲利
                                            if (realized_trade_long_profitratio>ls_max_gain) {
                                                ls_max_gain=realized_trade_long_profitratio;
                                            }
                                            if (realized_trade_short_profitratio>ls_max_gain) {
                                                ls_max_gain=realized_trade_short_profitratio;
                                            }
                                            //多空最大損失
                                            if (realized_trade_long_profitratio<ls_max_loss) {
                                                ls_max_loss=realized_trade_long_profitratio;
                                            }
                                            if (realized_trade_short_profitratio<ls_max_loss) {
                                                ls_max_loss=realized_trade_short_profitratio;
                                            }
                                        }
                                        
                                        //2.更新最新資料
                                        BS_last=BS_1;
                                        enter_price=open;
                                        
                                        
                                    }
                                    //有買賣動作之後，本期計算出未實現損益
                                    
                                    //NSLog(@"BS_last= %i",BS_last);
                                    if (BS_last  ==1 && enter_price>0) {
                                        //做多未實現損益
                                        last_trade_long_profitratio =(close-enter_price)/enter_price*100 ;
                                    }
                                    else if(BS_last  == -1 && enter_price>0){
                                        //做空未實現損益
                                        last_trade_short_profitratio =(enter_price-close)/enter_price*100 ;
                                        
                                    }
                                    else{
                                        last_trade_long_profitratio=0;
                                        last_trade_short_profitratio=0;
                                        
                                    }
                                    
                                    
                                    //NSLog(@"last_trade_long_profitratio= %f",last_trade_long_profitratio);
                                    
                                    
                                    //停損機制
                                    //判斷是否需要停損
                                    if (isUse_Stop==1) {
                                        
                                        if (Stop_ratio*-100>last_trade_long_profitratio) {
                                            //做多未實現損益超過停損率 下期停損掉
                                            BS_Stop=-2;
                                            
                                            // NSLog(@"BS_Stop=-2 %f",enter_price);
                                            // NSLog(@"slow=%f fast=%f",SlowLim,FastLim);
                                            // NSLog(@"last_trade_long_profitratio=%f",last_trade_long_profitratio);
                                            
                                        }
                                        else if (Stop_ratio*-100>last_trade_short_profitratio){
                                            //做空未實現損益超過停損率 下期停損掉
                                            BS_Stop=2;
                                            
                                        }
                                        else{
                                            BS_Stop=0;
                                        }
                                        
                                    }
                                    
                                    
                                    
                                    //3.年限
                                    NSDate *date_0;
                                    date_0=[his_dic_0 objectForKey:HIS_basic_date];
                                    
                                    NSDate  *date_now;
                                    date_now=[his_dic objectForKey:HIS_basic_date];
                                    
                                    double l;
                                    
                                    l=[date_now timeIntervalSinceDate:date_0]/86400;
                                    
                                    year=l/365;
                                    
                                    
                                    //4.報酬率
                                    {
                                        //作多年化報酬率
                                        return_long=realized_trade_long_profitratio_sum/year;
                                        
                                        //作空年化報酬率
                                        return_short=realized_trade_short_profitratio_sum/year;
                                        
                                        //多空年化報酬率
                                        return_ls=(realized_trade_long_profitratio_sum+realized_trade_short_profitratio_sum)/year;
                                        
                                    }
                                    
                                }
                                
                            }
                            
                            
                            //5.儲存
                            {
                                //基本資料
                                {
                                    [temp_cal setObject:[NSNumber numberWithDouble:price] forKey:HIS_dic_temp_price];
                                    [temp_cal setObject:[NSNumber numberWithDouble:Smooth] forKey:HIS_dic_temp_Smooth];
                                    [temp_cal setObject:[NSNumber numberWithDouble:Detrender] forKey:HIS_dic_temp_Detrender];
                                    [temp_cal setObject:[NSNumber numberWithDouble: Q1] forKey:HIS_dic_temp_Q1];
                                    [temp_cal setObject:[NSNumber numberWithDouble: l1] forKey:HIS_dic_temp_l1];
                                    [temp_cal setObject:[NSNumber numberWithDouble: jl] forKey:HIS_dic_temp_jl];
                                    [temp_cal setObject:[NSNumber numberWithDouble: jQ] forKey:HIS_dic_temp_jQ];
                                    [temp_cal setObject:[NSNumber numberWithDouble: l2] forKey:HIS_dic_temp_l2];
                                    [temp_cal setObject:[NSNumber numberWithDouble: Q2] forKey:HIS_dic_temp_Q2];
                                    [temp_cal setObject:[NSNumber numberWithDouble: Re] forKey:HIS_dic_temp_Re];
                                    [temp_cal setObject:[NSNumber numberWithDouble:lm] forKey:HIS_dic_temp_lm];
                                    [temp_cal setObject:[NSNumber numberWithDouble:Period] forKey:HIS_dic_temp_Period];
                                    [temp_cal setObject:[NSNumber numberWithDouble:SmoothPeriod] forKey:HIS_dic_temp_SmoothPeriod];
                                    [temp_cal setObject:[NSNumber numberWithDouble:Phase] forKey:HIS_dic_temp_Phase];
                                    [temp_cal setObject:[NSNumber numberWithDouble:DeltaPhase] forKey:HIS_dic_temp_DeltaPhase];
                                    [temp_cal setObject:[NSNumber numberWithDouble:alpha] forKey:HIS_dic_temp_alpha];
                                    [temp_cal setObject:[NSNumber numberWithDouble:FAMA] forKey:HIS_dic_temp_FAMA];
                                    [temp_cal setObject:[NSNumber numberWithDouble:MAMA] forKey:HIS_dic_temp_MAMA];
                                }
                                
                                //買賣訊號
                                {
                                    [temp_cal setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_MESA_BS];
                                    
                                    [temp_cal setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_MESA_State];
                                    
                                    
                                    //停損機制 最佳化
                                    [temp_cal setObject:[NSNumber numberWithDouble: BS_Stop] forKey:CL_his_data_signal_MESA_BS_Stop];
                                    
                                }
                                //損益分析計算需要
                                {
                                    //最後一筆買賣方向
                                    [temp_cal setObject:[NSNumber numberWithInt:BS_last] forKey:HIS_dic_temp_profit_bs];
                                    
                                    
                                    
                                    //最後一筆進場價位
                                    [temp_cal setObject:[NSNumber numberWithDouble:enter_price] forKey:HIS_dic_temp_profit_enterprice];
                                    
                                    
                                }
                                
                                //損益
                                {
                                    //做多未實現損益
                                    [temp_cal setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_MESA_longratio_lasttrade];
                                    //做空未實現損益
                                    [temp_cal setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_MESA_shortratio_lasttrade];
                                    
                                    
                                    
                                    
                                    //做多已經實現損益合計
                                    [temp_cal setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA_longratio_realizedtrade_temp];
                                    //做空已經實現損益合計
                                    [temp_cal setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA_shortratio_realizedtrade_temp];
                                    
                                    
                                    //做多總交易次數
                                    [temp_cal setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_MESA_long_total_count_temp];
                                    //做多賺錢次數
                                    [temp_cal setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_MESA_long_win_count_temp];
                                    //做多勝率
                                    [temp_cal setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_MESA_long_win_ratio_temp];
                                    
                                    
                                    //做空總交易次數
                                    [temp_cal setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_MESA_short_total_count_temp];
                                    //做空賺錢次數
                                    [temp_cal setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_MESA_short_win_count_temp];
                                    //做空勝率
                                    [temp_cal setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_MESA_short_win_ratio_temp];
                                    
                                    
                                    
                                    //多空總交易次數
                                    [temp_cal setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_MESA_LS_total_count_temp];
                                    //多空賺錢次數
                                    [temp_cal setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_MESA_LS_win_count_temp];
                                    //多空勝率
                                    [temp_cal setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_MESA_LS_win_ratio_temp];
                                    
                                    //做多最大獲利率
                                    [temp_cal setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_MESA_long_max_gain_temp];
                                    
                                    
                                    
                                    //做多最大虧損率
                                    [temp_cal setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_MESA_long_max_loss_temp];
                                    
                                    //做空最大獲利率
                                    [temp_cal setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_MESA_short_max_gain_temp];
                                    
                                    //做空最大虧損率
                                    [temp_cal setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_MESA_short_max_loss_temp];
                                    
                                    //多空最大獲利率
                                    [temp_cal setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_MESA_LS_max_gain_temp  ];
                                    
                                    //多空最大虧損率
                                    [temp_cal setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_MESA_LS_max_loss_temp];
                                    
                                    //作多年間
                                    [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA_long_period_temp];
                                    //作空年間
                                    [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA_short_period_temp];
                                    //多空年間
                                    [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA_LS_period_temp];
                                    
                                    
                                    //作多年化報酬率
                                    [temp_cal setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_MESA_long_return_temp];
                                    //作空年化報酬率
                                    [temp_cal setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_MESA_short_return_temp];
                                    //多空年化報酬率
                                    [temp_cal setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_MESA_LS_return_temp];
                                    
                                }
                                
                            }
                            
                            
                            
                        }
                        
                        
                        
                        
                    }
                    
                    
                    
                }
                
                //b.取出當筆損益的結果
                {
                    
                    
                    NSMutableDictionary *opt_data=[[NSMutableDictionary alloc]init];
                    
                    //參數
                    [opt_data setObject:[NSNumber numberWithDouble:SlowLim] forKey:@"SlowLim"];
                    [opt_data setObject:[NSNumber numberWithDouble:FastLim] forKey:@"FastLim"];
                    
                    //計算損益結果
                    {
                        
                        //做多未實現損益
                        [opt_data setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_MESA_longratio_lasttrade];
                        //做空未實現損益
                        [opt_data setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_MESA_shortratio_lasttrade];
                        
                        
                        
                        //做多勝率
                        [opt_data setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_MESA_long_win_ratio_temp];
                        
                        //作多年化報酬率
                        [opt_data setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_MESA_long_return_temp];
                        
                        //做多總交易次數
                        [opt_data setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_MESA_long_total_count_temp];
                        
                        
                        //做多已經實現損益合計
                        [opt_data setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_MESA_longratio_realizedtrade_temp];
                        //做空已經實現損益合計
                        [opt_data setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_MESA_shortratio_realizedtrade_temp];
                        
                        
                        
                        //做多賺錢次數
                        [opt_data setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_MESA_long_win_count_temp];
                        
                        
                        
                        //做空總交易次數
                        [opt_data setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_MESA_short_total_count_temp];
                        //做空賺錢次數
                        [opt_data setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_MESA_short_win_count_temp];
                        //做空勝率
                        [opt_data setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_MESA_short_win_ratio_temp];
                        
                        
                        
                        //多空總交易次數
                        [opt_data setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_MESA_LS_total_count_temp];
                        //多空賺錢次數
                        [opt_data setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_MESA_LS_win_count_temp];
                        //多空勝率
                        [opt_data setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_MESA_LS_win_ratio_temp];
                        
                        //做多最大獲利率
                        [opt_data setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_MESA_long_max_gain_temp];
                        
                        
                        
                        //做多最大虧損率
                        [opt_data setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_MESA_long_max_loss_temp];
                        
                        //做空最大獲利率
                        [opt_data setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_MESA_short_max_gain_temp];
                        
                        //做空最大虧損率
                        [opt_data setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_MESA_short_max_loss_temp];
                        
                        //多空最大獲利率
                        [opt_data setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_MESA_LS_max_gain_temp  ];
                        
                        //多空最大虧損率
                        [opt_data setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_MESA_LS_max_loss_temp];
                        
                        //作多年間
                        [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA_long_period_temp];
                        //作空年間
                        [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA_short_period_temp];
                        //多空年間
                        [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_MESA_LS_period_temp];
                        
                        
                        
                        //作空年化報酬率
                        [opt_data setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_MESA_short_return_temp];
                        //多空年化報酬率
                        [opt_data setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_MESA_LS_return_temp];
                        
                        
                        
                        
                        
                        
                    }
                    
                    [optimize_data_dic addObject:opt_data];
                    [opt_data release];
                    
                    
                    
                }
                
                //c.清除計算暫存記憶體 HIS_optimize_temp
                for (NSMutableDictionary *his_dic in his_dic_serial) {
                    
                    NSDate *now=[his_dic objectForKey:HIS_basic_date];
                    
                    //判斷區間內
                    if ([now compare:start]==NSOrderedDescending  && [now compare:end]==NSOrderedAscending) {
                        
                        [his_dic removeObjectForKey:HIS_optimize_temp];
                        
                    }
                    
                }
                
                
                [pool release];
                
            }
            
        }
        
        //3.針對計算結果排序 取出 mes1 mesa2 mesa3 參數
        //最佳化準則
        NSArray *sortedArray_count_final =nil;//最後排序結果
        {
            /* 選取最佳化參數原則：
             每檔股票參數的選取理論：因為有些股票的走勢只有走ㄧ大波,也許兩年才有依次大行情,
			 如果是以報酬率為先選擇標準,這樣會有偏誤,所以第一個是以勝率為準,這樣的話
			 系統比較穩定與客觀,之後則再以報酬率,交易次數為篩選標準,最後交易次數應該是
			 以越多交易次數越多越佳,主要還是避免幾次的大賺,雖然可能造成交易次數過多
             產業群組內,挑選哪檔股票當作程式交易的標準:以報酬率為優先考慮,主要是因為在參數篩選過程中
             已經先考慮到單次獲利太高的問題,且當然要選報酬率越高的股票當作標準
             */
            
            //NSLog(@"計算結果=%@",optimize_data_dic);
            NSString *sWin_ratio;
            NSString *sReturn;
            NSString *sCount;
            if (compare_method==0) {
                sWin_ratio=CL_his_data_profit_MESA_long_win_ratio_temp;
                sReturn=CL_his_data_profit_MESA_long_return_temp;
                sCount=CL_his_data_profit_MESA_long_total_count_temp;
            }
            else if (compare_method==1){
                sWin_ratio=CL_his_data_profit_MESA_short_win_ratio_temp;
                sReturn=CL_his_data_profit_MESA_short_return_temp;
                sCount=CL_his_data_profit_MESA_short_total_count_temp;
            }
            else if (compare_method==2){
                sWin_ratio=CL_his_data_profit_MESA_LS_win_ratio_temp;
                sReturn=CL_his_data_profit_MESA_LS_return_temp;
                sCount=CL_his_data_profit_MESA_LS_total_count_temp;
            }
            else{
                sWin_ratio=CL_his_data_profit_MESA_LS_win_ratio_temp;
                sReturn=CL_his_data_profit_MESA_LS_return_temp;
                sCount=CL_his_data_profit_MESA_LS_total_count_temp;
            }
            
            //NSLog(@"比較準則=%i %@ %@ %@",compare_method,sWin_ratio,sReturn,sCount);
            
            //a.勝率排序
            NSArray *sortedArray_win_ratio =nil;
            sortedArray_win_ratio= [ optimize_data_dic  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                
                NSNumber *lastName1 = [firstObject objectForKey:sWin_ratio] ;
                NSNumber *lastName2 = [secondObject objectForKey:sWin_ratio] ;
                
                return [lastName2 compare: lastName1];
                
            }];
            
            //b.取出勝率前30名的
			NSMutableArray *sortWinPercentage_top;
            int top_win_ratio=30;
			sortWinPercentage_top=[[NSMutableArray alloc] init];
			for (int k=0 ; k<=top_win_ratio ; k++) {
				[sortWinPercentage_top addObject: [sortedArray_win_ratio objectAtIndex:k ]  ];
			}
            
            //c.依照年報酬率排序
            
            NSArray *sortedArray_return =nil;
            sortedArray_return= [ sortWinPercentage_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                
                NSNumber *lastName1 = [firstObject objectForKey:sReturn] ;
                NSNumber *lastName2 = [secondObject objectForKey:sReturn] ;
                
                return [lastName2 compare: lastName1];
                
            }];
            
            //d.取出年報酬率前15名的
            NSMutableArray *sortReturn_top;
            int top_return=15;
            sortReturn_top=[[NSMutableArray alloc] init];
            for (int k=0 ; k<=top_return ; k++) {
				[sortReturn_top addObject: [sortedArray_return objectAtIndex:k ]  ];
			}
            
            
            //e.對交易次數排序
            
            sortedArray_count_final= [ sortReturn_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                
                NSNumber *lastName1 = [firstObject objectForKey:sCount] ;
                NSNumber *lastName2 = [secondObject objectForKey:sCount] ;
                
                return [lastName2 compare: lastName1];
                
            }];
            
            [sortWinPercentage_top release];
            [sortReturn_top release];
            
            
        }
        
        //4.儲存最佳化後的參數
        {
            NSLog(@"排序循環數目 =%i",count_loop);
            //NSLog(@"排序結果 =%@",sortedArray_count_final);
            
            int middle=[sortedArray_count_final count]/2;
            NSMutableDictionary *dic1=[sortedArray_count_final objectAtIndex:0];
            NSMutableDictionary *dic2=[sortedArray_count_final objectAtIndex:middle];
            NSMutableDictionary *dic3= [sortedArray_count_final objectAtIndex:[sortedArray_count_final count]-1];
            
            // NSLog(@"mesa1=%@",dic1);
            // NSLog(@"mesa2=%@",dic2);
            // NSLog(@"mesa3=%@",dic3);
            
            //存入日的週期的參數資料庫內
            NSString *DWM=day;
            
            //mesa1
            {
                NSMutableDictionary *para_value_dic1=[[[NSMutableDictionary alloc]init ] autorelease];
                double sSlowLim1,sFastLim1;
                sSlowLim1=[[dic1 objectForKey:@"SlowLim"] doubleValue];
                sFastLim1=[[dic1 objectForKey:@"FastLim"] doubleValue];
                
                [para_value_dic1 setObject:[NSNumber numberWithDouble:sSlowLim1] forKey:Para_1];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:sFastLim1] forKey:Para_2];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:0] forKey:Para_3];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:0] forKey:Para_4];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic1 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic1 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_MESA1 Para_dic:para_value_dic1 period:DWM];
            }
            
            //mesa2
            {
                
                NSMutableDictionary *para_value_dic2=[[[NSMutableDictionary alloc]init ] autorelease];
                double sSlowLim2,sFastLim2;
                sSlowLim2=[[dic2 objectForKey:@"SlowLim"] doubleValue];
                sFastLim2=[[dic2 objectForKey:@"FastLim"] doubleValue];
                
                [para_value_dic2 setObject:[NSNumber numberWithDouble:sSlowLim2] forKey:Para_1];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:sFastLim2] forKey:Para_2];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:0] forKey:Para_3];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:0] forKey:Para_4];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic2 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic2 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_MESA2 Para_dic:para_value_dic2 period:DWM];
                
            }
            
            //mesa3
            {
                
                NSMutableDictionary *para_value_dic3=[[[NSMutableDictionary alloc]init ] autorelease];
                double sSlowLim3,sFastLim3;
                sSlowLim3=[[dic3 objectForKey:@"SlowLim"] doubleValue];
                sFastLim3=[[dic3 objectForKey:@"FastLim"] doubleValue];
                
                [para_value_dic3 setObject:[NSNumber numberWithDouble:sSlowLim3] forKey:Para_1];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:sFastLim3] forKey:Para_2];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:0] forKey:Para_3];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:0] forKey:Para_4];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic3 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic3 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                
                [[self data_object_para] Save_Para: Defaults_Calculate_MESA3 Para_dic:para_value_dic3 period:DWM];
            }
            
            
            
        }
        
        //5.重算資料
        {
            
            //NSLog(@"參數最佳化後，重新計算所有資料");
            //重新計算內存數據
            [self re_calculate_history_indicator_signal];
            
            //報價表更新
            // NSLog(@"最佳化成功 但是尚未完成重新顯示走勢圖或表格 的更新");
            
            
            //公告最佳化個股結束
            {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                
                [dict setObject:self forKey:@"dataobject"];
                
                NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:NOT_sheet_para_optimize_finize
                                  object:self
                                userInfo: dict   ];
                
            }
            
            
            
            
        }
        
        //6.清除每筆計算結果資料
        [optimize_data_dic release];
        
    }
    
    
}
-(void)optimize_LF:(NSMutableDictionary *)para_dic{
    
    
    NSLog(@"最佳化：lf");
    //1.取出日期區間
    NSDate *start;
    NSDate *end;
    {
        
        start=[para_dic objectForKey:Para_Optimize_date_start];
        end= [para_dic objectForKey:Para_Optimize_date_end];
        
        
        NSLog(@"開始=%@", start);
        NSLog(@"結束=%@", end );
    }
    
    //2.取出歷史資料
    NSMutableArray *his_dic_serial=[self get_his_data_serial];
    if (his_dic_serial) {
        //1.參數
        float longRatio_start,shortRatio_start;
        float longRatio_end,shortRatio_end;
        float longRatio_step,shortRatio_step;
        
        int longDay_start,shortDay_start;
        int longDay_end,shortDay_end;
        int longDay_step,shortDay_step;
        
        float long_cost,short_cost;//買進與賣出交易成本
        
        
        float Stop_ratio;           //停損率
        int isUse_Stop;             //是否停損
        
        
        int compare_method;
        {
            //技術指標循環參數
            longRatio_start= [[para_dic objectForKey:Para_Default_start_1] floatValue];
            longRatio_end= [[para_dic objectForKey:Para_Default_end_1] floatValue];
            longRatio_step= [[para_dic objectForKey:Para_Default_step_1] floatValue];
            
            longDay_start= [[para_dic objectForKey:Para_Default_start_2] floatValue];
            longDay_end= [[para_dic objectForKey:Para_Default_end_2] floatValue];
            longDay_step= [[para_dic objectForKey:Para_Default_step_2] floatValue];
              
            shortRatio_start= [[para_dic objectForKey:Para_Default_start_3] floatValue];
            shortRatio_end= [[para_dic objectForKey:Para_Default_end_3] floatValue];
            shortRatio_step= [[para_dic objectForKey:Para_Default_step_3] floatValue];
            
            shortDay_start= [[para_dic objectForKey:Para_Default_start_4] floatValue];
            shortDay_end= [[para_dic objectForKey:Para_Default_end_4] floatValue];
            shortDay_step= [[para_dic objectForKey:Para_Default_step_4] floatValue];
            
            
            NSLog(@"longRatio_start=%f longRatio_end=%f longRatio_step=%f",longRatio_start,longRatio_end ,longRatio_step);
            
            //比較準則
            compare_method= [[para_dic objectForKey:Para_Optimize_compare_method] intValue];
            
            
            long_cost= [[para_dic objectForKey:Para_Optimize_long_cost] floatValue];
            short_cost= [[para_dic objectForKey:Para_Optimize_short_cost] floatValue];
            
            //停損機制
            isUse_Stop= [[para_dic objectForKey:Para_Optimize_isUse_Stop] intValue];
            Stop_ratio= [[para_dic objectForKey:Para_Optimize_Stop_ratio] floatValue];
        }
    
        //2.進入參數循環        
        NSMutableArray *optimize_data_dic=[[NSMutableArray alloc]init]; //儲存每筆計算結果資料
        int count_loop=0; //計數器
        for (float longRatio=longRatio_start; longRatio<=longRatio_end; longRatio=longRatio+longRatio_step ) {
            
            for (float shortRatio=shortRatio_start; shortRatio<=shortRatio_end; shortRatio=shortRatio+shortRatio_step ) {
                
                
                for (int longDay=longDay_start; longDay<=longDay_end; longDay=longDay+longDay_step ) {
                    
                    for (int shortDay=shortDay_start; shortDay<=shortDay_end; shortDay=shortDay+shortDay_step ) {
                        
                        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                        count_loop++;
                        
                        //宣告損益計算變數
                        
                        double last_trade_long_profitratio;         //最後一筆做多獲利率
                        double last_trade_short_profitratio;        //最後一筆做空獲利率
                        
                        
                        double realized_trade_long_profitratio;     //已經實現做多損益
                        double realized_trade_short_profitratio;    //已經實現做空損益
                        double realized_trade_long_profitratio_sum; //已經實現做多損益合計
                        double realized_trade_short_profitratio_sum;//已經實現做空損益合計
                        
                        double long_total_count; //做多交易次數
                        double long_win_count;   //做多交易賺錢次數
                        double long_win_ratio;   //做多勝率
                        
                        double short_total_count; //做空交易次數
                        double short_win_count;   //做空交易賺錢次數
                        double short_win_ratio;   //做空勝率
                        
                        double ls_total_count; //多空交易次數
                        double ls_win_count;   //多空交易賺錢次數
                        double ls_win_ratio;   //多空勝率
                        
                        double long_max_gain; //做多最大獲利率
                        double long_max_loss; //做多最大虧損率
                        double short_max_gain; //做空最大獲利率
                        double short_max_loss; //做空最大虧損率
                        double ls_max_gain;  //多空最大獲利率
                        double ls_max_loss; //多空最大虧損率
                        
                        double year; //開始計算日期
                        
                        double return_long;// 作多年化報酬率
                        double return_short;// 作空年化報酬率
                        double return_ls;// 作空年化報酬率
                        {
                            
                            last_trade_long_profitratio=0;
                            last_trade_short_profitratio=0;
                            
                            
                            realized_trade_long_profitratio_sum=0;
                            realized_trade_short_profitratio_sum=0;
                            
                            long_total_count=0;
                            long_win_count=0;
                            long_win_ratio=0;
                            
                            short_total_count=0;
                            short_win_count=0;
                            short_win_ratio=0;
                            
                            ls_total_count=0;
                            ls_win_count=0;
                            ls_win_ratio=0;
                            
                            long_max_gain=0; //做多最大獲利率
                            long_max_loss=0; //做多最大虧損率
                            short_max_gain=0; //做空最大獲利率
                            short_max_loss=0; //做空最大虧損率
                            ls_max_gain=0;  //多空最大獲利率
                            ls_max_loss=0; //多空最大虧損率
                            
                            year=0;
                            
                            return_long=0;
                            return_short=0;
                            return_ls=0;
                            
                        }
                        
                        //a.進入每筆最佳化計算
                        
                        for (int i=0 ; i<[his_dic_serial count]; i++) {
                            
                            
                            NSMutableDictionary *his_dic =[his_data_serial objectAtIndex:i];
                            
                            NSDate *now=[his_dic objectForKey:HIS_basic_date];
                            
                            
                            //判斷區間內
                            if ([now compare:start]==NSOrderedDescending  && [now compare:end]==NSOrderedAscending) {
                                
                                //正式進入計算
                                
                                //建立 計算暫存記憶體空間
                                NSMutableDictionary *temp_cal=[[NSMutableDictionary alloc] init];
                                
                                [his_dic setObject:temp_cal forKey:HIS_optimize_temp];
                                
                                [temp_cal release];
                                
                                //開始計算
                                {
                                    
                                    //1.開高收低 基本每筆資料
                                    double   open  ;
                                    double  close;
                                    {
                                        //調整收盤價比率
                                        double adj_ratio;
                                        {
                                            double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
                                            double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                                            
                                            
                                            if (isUseAdjClose==YES) {
                                                adj_ratio=adj_close/close;
                                            }
                                            else{
                                                adj_ratio=1;
                                            }
                                        }
                                        
                                         
                                        open=[[his_dic objectForKey:HIS_basic_open] doubleValue]* adj_ratio;
                                        close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
                                        
                                    }
                                    
                                    //2.計算用的變數
                                    float LF_bout;
                                    float LF_sout;
                                    int LF_b;
                                    int LF_s;
                                    int LF_b_1;
                                    int LF_s_1;
                                    
                                    //3.計算LF
                                    {
                                        if (i>longDay && i>shortDay) {
                                            
                                            if (i>=1) {
                                           
                                                LF_bout= [self get_his_temp_optimize_value:HIS_dic_temp_LF_bout i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_sout= [self get_his_temp_optimize_value:HIS_dic_temp_LF_sout i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_b=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_b i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_s=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_s i:i-1 historyData:his_dic_serial] ;
                                                
                                                //紀錄上一期
                                                LF_b_1=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_b i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_s_1=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_s i:i-1 historyData:his_dic_serial] ;
                                                
                                                
                                                
                                            }
                                            else{
                                                LF_bout=0;
                                                LF_sout=0;
                                                LF_b=0;
                                                LF_s=0;
                                                LF_b_1=0;
                                                LF_s_1=0;
                                                
                                                
                                            }
                                            
                                            
                                            int start_i;
                                            {
                                                if (longDay>shortDay) {
                                                    start_i=longDay;
                                                }
                                                else{
                                                    start_i=shortDay;
                                                }
                                                
                                                
                                            }
                                            
                                            //做多區間
                                            float BRange;
                                            {
                                                float rhigh=0;
                                                float rlow=0;
                                                {
                                                    //區間最大值
                                                    for (int Hi=0;Hi<longDay ; Hi++) {
                                                        
                                                        if (Hi==0) {
                                                            
                                                            rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                        }
                                                        else{
                                                            if (rhigh<[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                                                
                                                                rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                                
                                                            }
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    //區間最小值
                                                    for (int Li=0;Li<longDay ; Li++) {
                                                        
                                                        if (Li==0) {
                                                            
                                                            rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                        }
                                                        else{
                                                            
                                                            if (rlow>[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                                                
                                                                rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                                
                                                            }
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    
                                                    
                                                }
                                                BRange=rhigh-rlow;
                                            }
                                            
                                            //做空區間
                                            float SRange;
                                            {
                                                float rhigh=0;
                                                float rlow=0;
                                                {
                                                    //區間最大值
                                                    for (int Hi=0;Hi<shortDay ; Hi++) {
                                                        
                                                        if (Hi==0) {
                                                            
                                                            rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                        }
                                                        else{
                                                            if (rhigh<[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                                                
                                                                rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                                
                                                            }
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    //區間最小值
                                                    for (int Li=0;Li<shortDay ; Li++) {
                                                        
                                                        if (Li==0) {
                                                            
                                                            rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                        }
                                                        else{
                                                            
                                                            if (rlow>[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                                                
                                                                rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                                
                                                            }
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    
                                                }
                                                
                                                SRange=rhigh-rlow;
                                            }
                                            
                                            {
                                                
                                                float close=[[[his_dic_serial objectAtIndex:i] objectForKey:HIS_basic_adjclose] doubleValue];
                                                
                                              // NSLog(@"%i %i",i,start_i);
                                                if (LF_b==0 && LF_s==0  ) {
                                                   
                                                    LF_b=1;
                                                    LF_s=0;
                                                    LF_bout=close-BRange*longRatio;
                                                    LF_sout=0;
                                                }
                                                else if (LF_b==1 && LF_bout+BRange<close) {
                                                    
                                                    LF_bout=LF_bout+BRange*longRatio;
                                                }
                                                else if (LF_b==1 && close<LF_bout) {
                                                     
                                                    LF_b=0;
                                                    LF_s=1;
                                                    LF_sout=close+SRange*shortRatio;
                                                    LF_bout=0;
                                                }
                                                                                               
                                                else if (LF_s==1 && LF_sout-SRange>close) {
                                                    LF_sout=LF_sout-SRange*shortRatio;
                                                }
                                                else if (LF_s==1 && close>LF_sout) {
                                                    LF_s=0;
                                                    LF_b=1;
                                                    LF_bout=close-BRange*longRatio;
                                                    LF_sout=0;
                                                }
                                                // NSLog(@"%i %i",LF_b,LF_s);
                                                
                                                
                                            }
                                            
                                            
                                            
                                        }
                                        else{
                                            
                                            LF_b=1;
                                            LF_s=0;
                                            LF_bout=[[[his_dic_serial objectAtIndex:i] objectForKey:HIS_basic_high] doubleValue]*(1-longRatio);
                                            LF_sout=0;
                                            LF_b_1=0;
                                            LF_s_1=0;
                                        }
                                        
                                        
                                        
                                    }
                                    
                                    //4.訊號判斷
                                    int BuyOrSell;      //此位置 i 是否要買或賣
                                    int Position_State; //此位置 i 多空狀態
                                    int BS_Stop; //停損機制 2表示做空停損 -2表示做多停損
                                    {
                                        BuyOrSell=0;
                                        Position_State=0;
                                        BS_Stop=0;
                                        
                                        if (i>0) {
                                            
                                            //買賣訊號
                                            if (LF_b_1==1 && LF_s==1) {
                                                BuyOrSell=-1;
                                                
                                            }
                                            else if (LF_s_1==1 && LF_b==1) {
                                                BuyOrSell=1;
                                            }
                                            else {
                                                BuyOrSell=0;
                                            }
                                            
                                            //狀態
                                            if (LF_s==1) {
                                                Position_State=-1;
                                            }
                                            else {
                                                Position_State=1;
                                            }
                                            
                                            
                                        }
                                        //NSLog(@"Position_State=%i",Position_State );
                                        
                                    }
                                    
                                    
                                    //6.損益部位                                     
                                    int BS_last ;// 最後一期買賣方向 因為是以隔天開盤價作為當期買賣價位
                                    double enter_price; //最後一期買進場價位
                                    {
                                        //變數歸0
                                        {
                                            last_trade_long_profitratio=0;
                                            last_trade_short_profitratio=0;
                                            
                                            realized_trade_long_profitratio=0;
                                            realized_trade_short_profitratio=0;
                                            
                                            realized_trade_long_profitratio_sum=0;
                                            realized_trade_short_profitratio_sum=0;
                                            
                                            long_total_count=0;
                                            long_win_count=0;
                                            long_win_ratio=0;
                                            
                                            short_total_count=0;
                                            short_win_count=0;
                                            short_win_ratio=0;
                                            
                                            ls_total_count=0;
                                            ls_win_count=0;
                                            ls_win_ratio=0;
                                            
                                            long_max_gain=0; //做多最大獲利率
                                            long_max_loss=0; //做多最大虧損率
                                            short_max_gain=0; //做空最大獲利率
                                            short_max_loss=0; //做空最大虧損率
                                            ls_max_gain=0;  //多空最大獲利率
                                            ls_max_loss=0; //多空最大虧損率
                                            
                                            
                                            BS_last=0;
                                            enter_price=0;
                                            year=0;
                                            
                                            return_long=0;
                                            return_short=0;
                                            return_ls=0;
                                        }
                                        
                                        if (i>0) {
                                            
                                            
                                            int BS_1 ;// 前一期買賣動作方向 因為是以隔天開盤價作為當期買賣價位
                                            
                                            //停損機制 最佳化
                                            int BS_Stop_1; //前一期是否有出現停損動作
                                            //BS_Stop_1=0;
                                            
                                            //1.取出前一期的資料
                                            NSMutableDictionary *his_dic_1=[his_data_serial objectAtIndex:i-1];//前一筆
                                            NSMutableDictionary *his_dic_0=[his_data_serial objectAtIndex:0];  //第0筆
                                            
                                            
                                            {
                                                
                                                //停損機制 最佳化
                                                //前一期是否有出現停損動作
                                                BS_Stop_1=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_signal_LF_BS_Stop] intValue];
                                                
                                                
                                                //前一期 買賣動作方向
                                                BS_1=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_signal_LF_BS] intValue];
                                                
                                                
                                                
                                                //前一期 已經實現做多合計
                                                realized_trade_long_profitratio_sum=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_longratio_realizedtrade_temp] doubleValue];
                                                
                                                
                                                
                                                //前一期 已經實現做空合計
                                                realized_trade_short_profitratio_sum=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_shortratio_realizedtrade_temp] doubleValue];
                                                
                                                //前一期 做多交易次數
                                                long_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_total_count_temp] doubleValue];
                                                
                                                //前一期 做多賺錢交易次數
                                                long_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_win_count_temp] doubleValue];
                                                
                                                //前一期 做多勝率
                                                long_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_win_ratio_temp] doubleValue];
                                                
                                                
                                                //前一期 做空交易次數
                                                short_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_total_count_temp] doubleValue];
                                                
                                                //前一期 做空賺錢交易次數
                                                short_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_win_count_temp] doubleValue];
                                                
                                                //前一期 做空勝率
                                                short_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_win_ratio_temp] doubleValue];
                                                
                                                
                                                //前一期 多空交易次數
                                                ls_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_total_count_temp] doubleValue];
                                                
                                                //前一期 多空賺錢交易次數
                                                ls_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_win_count_temp] doubleValue];
                                                
                                                //前一期 多空勝率
                                                ls_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_win_ratio_temp] doubleValue];
                                                
                                                //做多最大獲利率
                                                long_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_max_gain_temp] doubleValue];
                                                
                                                //做多最大虧損率
                                                long_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_max_loss_temp] doubleValue];
                                                
                                                //做空最大獲利率
                                                short_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_max_gain_temp] doubleValue];
                                                
                                                //做空最大虧損率
                                                short_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_max_loss_temp] doubleValue];
                                                
                                                //多空最大獲利率
                                                ls_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_max_gain_temp] doubleValue];
                                                
                                                //多空最大虧損率
                                                ls_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_max_loss_temp] doubleValue];
                                                
                                                
                                                
                                                
                                            }
                                            
                                            
                                            //2.判斷上一期是否有買賣動作
                                            if (BS_1==0) {
                                                
                                                
                                                enter_price=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice  i:i-1 historyData:his_dic_serial] ;
                                                
                                                
                                                //停損機制 最佳化
                                                //前一期是否需要停損
                                                if (BS_Stop_1==-2 ) {
                                                    
                                                    //NSLog(@"BS_Stop_1==-2");
                                                    
                                                    //前一期出現需要做多停損訊號
                                                    BS_last=0;
                                                    //作多出場損益
                                                    {
                                                        //做多最近一筆 含有交易成本
                                                        realized_trade_long_profitratio=(open-enter_price)/enter_price*100-(long_cost+short_cost)*100;
                                                        
                                                        
                                                        
                                                        //累計做多
                                                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                                                        
                                                        //累計做多交易次數
                                                        long_total_count=long_total_count+1;
                                                        
                                                        //做多交易賺錢次數
                                                        if (realized_trade_long_profitratio>0) {
                                                            //賺錢才可以+1
                                                            long_win_count=long_win_count+1;
                                                        }
                                                        else{
                                                            long_win_count=long_win_count;
                                                        }
                                                        
                                                        //勝率
                                                        if (long_total_count>0) {
                                                            long_win_ratio= long_win_count/long_total_count*100;
                                                        }
                                                        else{
                                                            long_win_ratio=0;
                                                        }
                                                        
                                                        //做多最大獲利
                                                        if (realized_trade_long_profitratio>long_max_gain) {
                                                            long_max_gain=realized_trade_long_profitratio;
                                                        }
                                                        
                                                        //做多最大損失
                                                        if (realized_trade_long_profitratio<long_max_loss) {
                                                            long_max_loss=realized_trade_long_profitratio;
                                                        }
                                                        
                                                        
                                                    }
                                                    
                                                }
                                                else if (BS_Stop_1==2 ){
                                                    //前一期出現做空需要停損的訊號
                                                    BS_last=0;
                                                    //作空出場損益
                                                    {
                                                        //做空最近一筆 含有交易成本
                                                        realized_trade_short_profitratio=(enter_price-open)/enter_price*100-(long_cost+short_cost)*100;
                                                        
                                                        //累計做多
                                                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                                                        
                                                        
                                                        //累計做空交易次數
                                                        short_total_count=short_total_count+1;
                                                        
                                                        
                                                        //做空交易賺錢次數
                                                        if (realized_trade_short_profitratio>0) {
                                                            //賺錢才可以+1
                                                            short_win_count=short_win_count+1;
                                                        }
                                                        else{
                                                            short_win_count=short_win_count;
                                                        }
                                                        
                                                        //勝率
                                                        if (short_total_count>0) {
                                                            short_win_ratio= short_win_count/short_total_count*100;
                                                        }
                                                        else{
                                                            short_win_ratio=0;
                                                        }
                                                        
                                                        
                                                        //做空最大獲利
                                                        if (realized_trade_short_profitratio>short_max_gain) {
                                                            short_max_gain=realized_trade_short_profitratio;
                                                        }
                                                        
                                                        //做空最大損失
                                                        if (realized_trade_short_profitratio<short_max_loss) {
                                                            short_max_loss=realized_trade_short_profitratio;
                                                        }
                                                    }
                                                    
                                                }
                                                else{
                                                    /*
                                                     if (enter_price==0) {
                                                     NSLog(@"slow=%f fast=%f",SlowLim,FastLim);
                                                     }
                                                     */
                                                    
                                                    //表示上一期無買賣動作
                                                    
                                                    //取出最後一筆的狀態 在轉移到下一期
                                                    BS_last=[self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial] ;
                                                    
                                                }
                                                
                                                
                                            }
                                            else{
                                                
                                                //表示上一期有買賣動作
                                                
                                                //1.計算已經實現損益
                                                {
                                                    //上一期尚未動作之前的部位
                                                    int BS_last_unchange;        //上一期的部位方向
                                                    double enterprice_last_unchange;//上一期的部位的進場價格還尚未更新到本期的開盤價之前的資料
                                                    
                                                    BS_last_unchange=[self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial];
                                                    enterprice_last_unchange=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice  i:i-1 historyData:his_dic_serial];
                                                    
                                                    
                                                    //計算已經實現損益與累計實現損益
                                                    if (BS_last_unchange==1) {
                                                        
                                                        //做多最近一筆 含有交易成本
                                                        realized_trade_long_profitratio=(open-enterprice_last_unchange)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                                                        
                                                        //累計做多
                                                        realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                                                        
                                                        //累計做多交易次數
                                                        long_total_count=long_total_count+1;
                                                        
                                                        //做多交易賺錢次數
                                                        if (realized_trade_long_profitratio>0) {
                                                            //賺錢才可以+1
                                                            long_win_count=long_win_count+1;
                                                        }
                                                        else{
                                                            long_win_count=long_win_count;
                                                        }
                                                        
                                                        //勝率
                                                        
                                                        if (long_total_count>0) {
                                                            long_win_ratio= long_win_count/long_total_count*100;
                                                        }
                                                        else{
                                                            long_win_ratio=0;
                                                        }
                                                        
                                                        //做多最大獲利
                                                        if (realized_trade_long_profitratio>long_max_gain) {
                                                            long_max_gain=realized_trade_long_profitratio;
                                                        }
                                                        
                                                        //做多最大損失
                                                        if (realized_trade_long_profitratio<long_max_loss) {
                                                            long_max_loss=realized_trade_long_profitratio;
                                                        }
                                                        
                                                        
                                                    }
                                                    else if (BS_last_unchange==-1){
                                                        //做空最近一筆 含有交易成本
                                                        realized_trade_short_profitratio=(enterprice_last_unchange-open)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                                                        
                                                        //累計做多
                                                        realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                                                        
                                                        
                                                        //累計做空交易次數
                                                        short_total_count=short_total_count+1;
                                                        
                                                        
                                                        //做空交易賺錢次數
                                                        if (realized_trade_short_profitratio>0) {
                                                            //賺錢才可以+1
                                                            short_win_count=short_win_count+1;
                                                        }
                                                        else{
                                                            short_win_count=short_win_count;
                                                        }
                                                        
                                                        //勝率
                                                        if (short_total_count>0) {
                                                            short_win_ratio= short_win_count/short_total_count*100;
                                                        }
                                                        else{
                                                            short_win_ratio=0;
                                                        }
                                                        
                                                        
                                                        //做空最大獲利
                                                        if (realized_trade_short_profitratio>short_max_gain) {
                                                            short_max_gain=realized_trade_short_profitratio;
                                                        }
                                                        
                                                        //做空最大損失
                                                        if (realized_trade_short_profitratio<short_max_loss) {
                                                            short_max_loss=realized_trade_short_profitratio;
                                                        }
                                                        
                                                        
                                                        
                                                    }
                                                    
                                                    //多空合計
                                                    ls_total_count=long_total_count+short_total_count;
                                                    ls_win_count=long_win_count+short_win_count;
                                                    
                                                    if (ls_total_count>0) {
                                                        ls_win_ratio=ls_win_count/ls_total_count*100;
                                                    }
                                                    else{
                                                        ls_win_ratio=0;
                                                    }
                                                    
                                                    //多空最大獲利
                                                    if (realized_trade_long_profitratio>ls_max_gain) {
                                                        ls_max_gain=realized_trade_long_profitratio;
                                                    }
                                                    if (realized_trade_short_profitratio>ls_max_gain) {
                                                        ls_max_gain=realized_trade_short_profitratio;
                                                    }
                                                    //多空最大損失
                                                    if (realized_trade_long_profitratio<ls_max_loss) {
                                                        ls_max_loss=realized_trade_long_profitratio;
                                                    }
                                                    if (realized_trade_short_profitratio<ls_max_loss) {
                                                        ls_max_loss=realized_trade_short_profitratio;
                                                    }
                                                }
                                                
                                                //2.更新最新資料
                                                BS_last=BS_1;
                                                enter_price=open;
                                                
                                                
                                            }
                                            //有買賣動作之後，本期計算出未實現損益
                                            
                                            //NSLog(@"BS_last= %i",BS_last);
                                            if (BS_last  ==1 && enter_price>0) {
                                                //做多未實現損益
                                                last_trade_long_profitratio =(close-enter_price)/enter_price*100 ;
                                            }
                                            else if(BS_last  == -1 && enter_price>0){
                                                //做空未實現損益
                                                last_trade_short_profitratio =(enter_price-close)/enter_price*100 ;
                                                
                                            }
                                            else{
                                                last_trade_long_profitratio=0;
                                                last_trade_short_profitratio=0;
                                                
                                            }
                                            
                                            
                                            //NSLog(@"last_trade_long_profitratio= %f",last_trade_long_profitratio);
                                            
                                            
                                            //停損機制
                                            //判斷是否需要停損
                                            if (isUse_Stop==1) {
                                                
                                                if (Stop_ratio*-100>last_trade_long_profitratio) {
                                                    //做多未實現損益超過停損率 下期停損掉
                                                    BS_Stop=-2;
                                                    
                                                    // NSLog(@"BS_Stop=-2 %f",enter_price);
                                                    // NSLog(@"slow=%f fast=%f",SlowLim,FastLim);
                                                    // NSLog(@"last_trade_long_profitratio=%f",last_trade_long_profitratio);
                                                    
                                                }
                                                else if (Stop_ratio*-100>last_trade_short_profitratio){
                                                    //做空未實現損益超過停損率 下期停損掉
                                                    BS_Stop=2;
                                                    
                                                }
                                                else{
                                                    BS_Stop=0;
                                                }
                                                
                                            }
                                            
                                            
                                            
                                            //3.年限
                                            NSDate *date_0;
                                            date_0=[his_dic_0 objectForKey:HIS_basic_date];
                                            
                                            NSDate  *date_now;
                                            date_now=[his_dic objectForKey:HIS_basic_date];
                                            
                                            double l;
                                            
                                            l=[date_now timeIntervalSinceDate:date_0]/86400;
                                            
                                            year=l/365;
                                            
                                            
                                            //4.報酬率
                                            {
                                                //作多年化報酬率
                                                return_long=realized_trade_long_profitratio_sum/year;
                                                
                                                //作空年化報酬率
                                                return_short=realized_trade_short_profitratio_sum/year;
                                                
                                                //多空年化報酬率
                                                return_ls=(realized_trade_long_profitratio_sum+realized_trade_short_profitratio_sum)/year;
                                                
                                            }
                                            
                                        }
                                        
                                    }
                                    
                                    
                                    //5.儲存
                                    {
                                        //基本資料
                                        {
                                            [temp_cal setObject:[NSNumber numberWithDouble:LF_bout] forKey:HIS_dic_temp_LF_bout];
                                            [temp_cal setObject:[NSNumber numberWithDouble:LF_sout] forKey:HIS_dic_temp_LF_sout];
                                            [temp_cal setObject:[NSNumber numberWithInt: LF_b] forKey:HIS_dic_temp_LF_b];
                                            [temp_cal setObject:[NSNumber numberWithInt: LF_s] forKey:HIS_dic_temp_LF_s];
                                            
                                            
                                        }
                                        
                                        //買賣訊號
                                        {
                                            [temp_cal setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LF_BS];
                                            
                                            [temp_cal setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LF_State];
                                            
                                            
                                            //停損機制 最佳化
                                            [temp_cal setObject:[NSNumber numberWithDouble: BS_Stop] forKey:CL_his_data_signal_LF_BS_Stop];
                                            
                                        }
                                        //損益分析計算需要
                                        {
                                            //最後一筆買賣方向
                                            [temp_cal setObject:[NSNumber numberWithInt:BS_last] forKey:HIS_dic_temp_profit_bs];
                                            
                                            
                                            
                                            //最後一筆進場價位
                                            [temp_cal setObject:[NSNumber numberWithDouble:enter_price] forKey:HIS_dic_temp_profit_enterprice];
                                            
                                            
                                        }
                                        
                                        //損益
                                        {
                                            //做多未實現損益
                                            [temp_cal setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF_longratio_lasttrade];
                                            //做空未實現損益
                                            [temp_cal setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF_shortratio_lasttrade];
                                            
                                            
                                            
                                            
                                            //做多已經實現損益合計
                                            [temp_cal setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF_longratio_realizedtrade_temp];
                                            //做空已經實現損益合計
                                            [temp_cal setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF_shortratio_realizedtrade_temp];
                                            
                                            
                                            //做多總交易次數
                                            [temp_cal setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF_long_total_count_temp];
                                            //做多賺錢次數
                                            [temp_cal setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF_long_win_count_temp];
                                            //做多勝率
                                            
                                            [temp_cal setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF_long_win_ratio_temp];
                                            
                                            
                                            //做空總交易次數
                                            [temp_cal setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF_short_total_count_temp];
                                            //做空賺錢次數
                                            [temp_cal setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF_short_win_count_temp];
                                            //做空勝率
                                            [temp_cal setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF_short_win_ratio_temp];
                                            
                                            
                                            
                                            //多空總交易次數
                                            [temp_cal setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF_LS_total_count_temp];
                                            //多空賺錢次數
                                            [temp_cal setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF_LS_win_count_temp];
                                            //多空勝率
                                            [temp_cal setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF_LS_win_ratio_temp];
                                            
                                            //做多最大獲利率
                                            [temp_cal setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF_long_max_gain_temp];
                                            
                                            
                                            
                                            //做多最大虧損率
                                            [temp_cal setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF_long_max_loss_temp];
                                            
                                            //做空最大獲利率
                                            [temp_cal setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF_short_max_gain_temp];
                                            
                                            //做空最大虧損率
                                            [temp_cal setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF_short_max_loss_temp];
                                            
                                            //多空最大獲利率
                                            [temp_cal setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF_LS_max_gain_temp  ];
                                            
                                            //多空最大虧損率
                                            [temp_cal setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF_LS_max_loss_temp];
                                            
                                            //作多年間
                                            [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_long_period_temp];
                                            //作空年間
                                            [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_short_period_temp];
                                            //多空年間
                                            [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_LS_period_temp];
                                            
                                            
                                            //作多年化報酬率
                                            [temp_cal setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF_long_return_temp];
                                            //作空年化報酬率
                                            [temp_cal setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF_short_return_temp];
                                            //多空年化報酬率
                                            [temp_cal setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF_LS_return_temp];
                                            
                                        }
                                        
                                    }
                                    
                                    
                                    
                                }
                                
                                
                                
                                
                            }
                            
                            
                            
                        }
                        
                        //b.取出當筆損益的結果
                        {
                            //float longRatio=longRatio_start;
                            //float shortRatio=shortRatio_start;
                            //int longDay=longDay_start;
                            //int shortDay=shortDay_start;
                            NSMutableDictionary *opt_data=[[NSMutableDictionary alloc]init];
                            
                            //參數
                            [opt_data setObject:[NSNumber numberWithFloat:longRatio] forKey:@"longRatio"];
                            [opt_data setObject:[NSNumber numberWithFloat:shortRatio] forKey:@"shortRatio"];
                            
                            [opt_data setObject:[NSNumber numberWithInt:longDay] forKey:@"longDay"];
                            [opt_data setObject:[NSNumber numberWithInt:shortDay] forKey:@"shortDay"];
                            
                            //計算損益結果
                            {
                                
                                //做多未實現損益
                                [opt_data setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF_longratio_lasttrade];
                                //做空未實現損益
                                [opt_data setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF_shortratio_lasttrade];
                                
                                
                                
                                //做多勝率
                                [opt_data setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF_long_win_ratio_temp];
                                
                                //作多年化報酬率
                                [opt_data setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF_long_return_temp];
                                
                                //做多總交易次數
                                [opt_data setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF_long_total_count_temp];
                                
                                
                                //做多已經實現損益合計
                                [opt_data setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF_longratio_realizedtrade_temp];
                                //做空已經實現損益合計
                                [opt_data setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF_shortratio_realizedtrade_temp];
                                
                                
                                
                                //做多賺錢次數
                                [opt_data setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF_long_win_count_temp];
                                
                                
                                
                                //做空總交易次數
                                [opt_data setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF_short_total_count_temp];
                                //做空賺錢次數
                                [opt_data setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF_short_win_count_temp];
                                //做空勝率
                                [opt_data setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF_short_win_ratio_temp];
                                
                                
                                
                                //多空總交易次數
                                [opt_data setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF_LS_total_count_temp];
                                //多空賺錢次數
                                [opt_data setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF_LS_win_count_temp];
                                //多空勝率
                                [opt_data setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF_LS_win_ratio_temp];
                                
                                //做多最大獲利率
                                [opt_data setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF_long_max_gain_temp];
                                
                                
                                
                                //做多最大虧損率
                                [opt_data setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF_long_max_loss_temp];
                                
                                //做空最大獲利率
                                [opt_data setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF_short_max_gain_temp];
                                
                                //做空最大虧損率
                                [opt_data setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF_short_max_loss_temp];
                                
                                //多空最大獲利率
                                [opt_data setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF_LS_max_gain_temp  ];
                                
                                //多空最大虧損率
                                [opt_data setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF_LS_max_loss_temp];
                                
                                //作多年間
                                [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_long_period_temp];
                                //作空年間
                                [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_short_period_temp];
                                //多空年間
                                [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_LS_period_temp];
                                
                                
                                
                                //作空年化報酬率
                                [opt_data setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF_short_return_temp];
                                //多空年化報酬率
                                [opt_data setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF_LS_return_temp];
                                
                                
                                
                                
                                
                                
                            }
                            
                            [optimize_data_dic addObject:opt_data];
                            [opt_data release];
                            
                            
                            
                        }
                        
                        //c.清除計算暫存記憶體 HIS_optimize_temp
                        for (NSMutableDictionary *his_dic in his_dic_serial) {
                            
                            NSDate *now=[his_dic objectForKey:HIS_basic_date];
                            
                            //判斷區間內
                            if ([now compare:start]==NSOrderedDescending  && [now compare:end]==NSOrderedAscending) {
                                
                                [his_dic removeObjectForKey:HIS_optimize_temp];
                                
                            }
                            
                        }
                        
                        
                        [pool release];
                    }
                    
                }
                
                
                
                
            }
            
        
        }
        
        //3.針對計算結果排序 取出 mes1 LF2 LF3 參數
        //最佳化準則
        NSArray *sortedArray_count_final =nil;//最後排序結果
        {
            /* 選取最佳化參數原則：
             每檔股票參數的選取理論：因為有些股票的走勢只有走ㄧ大波,也許兩年才有依次大行情,
			 如果是以報酬率為先選擇標準,這樣會有偏誤,所以第一個是以勝率為準,這樣的話
			 系統比較穩定與客觀,之後則再以報酬率,交易次數為篩選標準,最後交易次數應該是
			 以越多交易次數越多越佳,主要還是避免幾次的大賺,雖然可能造成交易次數過多
             產業群組內,挑選哪檔股票當作程式交易的標準:以報酬率為優先考慮,主要是因為在參數篩選過程中
             已經先考慮到單次獲利太高的問題,且當然要選報酬率越高的股票當作標準
             */
            
            //NSLog(@"計算結果=%@",optimize_data_dic);
            NSString *sWin_ratio;
            NSString *sReturn;
            NSString *sCount;
            if (compare_method==0) {
                sWin_ratio=CL_his_data_profit_LF_long_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_long_return_temp;
                sCount=CL_his_data_profit_LF_long_total_count_temp;
            }
            else if (compare_method==1){
                sWin_ratio=CL_his_data_profit_LF_short_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_short_return_temp;
                sCount=CL_his_data_profit_LF_short_total_count_temp;
            }
            else if (compare_method==2){
                sWin_ratio=CL_his_data_profit_LF_LS_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_LS_return_temp;
                sCount=CL_his_data_profit_LF_LS_total_count_temp;
            }
            else{
                sWin_ratio=CL_his_data_profit_LF_LS_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_LS_return_temp;
                sCount=CL_his_data_profit_LF_LS_total_count_temp;
            }
            
            //NSLog(@"比較準則=%i %@ %@ %@",compare_method,sWin_ratio,sReturn,sCount);
            
            //a.勝率排序
            NSArray *sortedArray_win_ratio =nil;
            sortedArray_win_ratio= [ optimize_data_dic  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                
                NSNumber *lastName1 = [firstObject objectForKey:sWin_ratio] ;
                NSNumber *lastName2 = [secondObject objectForKey:sWin_ratio] ;
                
                return [lastName2 compare: lastName1];
                
            }];
            
            
            
            //b.取出勝率前30名的
			NSMutableArray *sortWinPercentage_top;
            int top_win_ratio=30;
			sortWinPercentage_top=[[NSMutableArray alloc] init];
			for (int k=0 ; k<=top_win_ratio ; k++) {
				[sortWinPercentage_top addObject: [sortedArray_win_ratio objectAtIndex:k ]  ];
			}
            
            //c.依照年報酬率排序
            
            NSArray *sortedArray_return =nil;
            sortedArray_return= [ sortWinPercentage_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                
                NSNumber *lastName1 = [firstObject objectForKey:sReturn] ;
                NSNumber *lastName2 = [secondObject objectForKey:sReturn] ;
                
                return [lastName2 compare: lastName1];
                
            }];
            
            //d.取出年報酬率前15名的
            NSMutableArray *sortReturn_top;
            int top_return=15;
            sortReturn_top=[[NSMutableArray alloc] init];
            for (int k=0 ; k<=top_return ; k++) {
				[sortReturn_top addObject: [sortedArray_return objectAtIndex:k ]  ];
			}
            
            
            //e.對交易次數排序
            
            sortedArray_count_final= [ sortReturn_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                
                NSNumber *lastName1 = [firstObject objectForKey:sCount] ;
                NSNumber *lastName2 = [secondObject objectForKey:sCount] ;
                
                return [lastName2 compare: lastName1];
                
            }];
            
            [sortWinPercentage_top release];
            [sortReturn_top release];
            
            
        }
        
        //4.儲存最佳化後的參數
        {
            //NSLog(@"排序循環數目 =%i",count_loop);
            //NSLog(@"排序結果 =%@",sortedArray_count_final);
            
            int middle=[sortedArray_count_final count]/2;
            NSMutableDictionary *dic1=[sortedArray_count_final objectAtIndex:0];
            NSMutableDictionary *dic2=[sortedArray_count_final objectAtIndex:middle];
            NSMutableDictionary *dic3= [sortedArray_count_final objectAtIndex:[sortedArray_count_final count]-1];
            
            // NSLog(@"mesa1=%@",dic1);
            // NSLog(@"mesa2=%@",dic2);
            // NSLog(@"mesa3=%@",dic3);
            
            //存入日的週期的參數資料庫內
            NSString *DWM=day;
            
            //LF1
            {
                NSMutableDictionary *para_value_dic1=[[[NSMutableDictionary alloc]init ] autorelease];
                float  slongRatio1,sshortRatio1;
                int    slongDay1,sshortDay1;
                
                slongRatio1=[[dic1 objectForKey:@"longRatio"] doubleValue];
                sshortRatio1=[[dic1 objectForKey:@"shortRatio"] doubleValue];
                slongDay1=[[dic1 objectForKey:@"longDay"] doubleValue];
                sshortDay1=[[dic1 objectForKey:@"shortDay"] doubleValue];
                
                
                
                [para_value_dic1 setObject:[NSNumber numberWithFloat: slongRatio1] forKey:Para_1];
                [para_value_dic1 setObject:[NSNumber numberWithInt:slongDay1] forKey:Para_2];
                [para_value_dic1 setObject:[NSNumber numberWithFloat:sshortRatio1] forKey:Para_3];
                [para_value_dic1 setObject:[NSNumber numberWithInt:sshortDay1] forKey:Para_4];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic1 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic1 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_LF1 Para_dic:para_value_dic1 period:DWM];
            }
            
            //LF2
            {
                NSMutableDictionary *para_value_dic2=[[[NSMutableDictionary alloc]init ] autorelease];
                float  slongRatio2,sshortRatio2;
                int    slongDay2,sshortDay2;
                
                slongRatio2=[[dic2 objectForKey:@"longRatio"] doubleValue];
                sshortRatio2=[[dic2 objectForKey:@"shortRatio"] doubleValue];
                slongDay2=[[dic2 objectForKey:@"longDay"] doubleValue];
                sshortDay2=[[dic2 objectForKey:@"shortDay"] doubleValue];
                
                
                
                [para_value_dic2 setObject:[NSNumber numberWithFloat: slongRatio2] forKey:Para_1];
                [para_value_dic2 setObject:[NSNumber numberWithInt:slongDay2] forKey:Para_2];
                [para_value_dic2 setObject:[NSNumber numberWithFloat:sshortRatio2] forKey:Para_3];
                [para_value_dic2 setObject:[NSNumber numberWithInt:sshortDay2] forKey:Para_4];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic2 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic2 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_LF2 Para_dic:para_value_dic2 period:DWM];
            }
            
            //LF3
            {
                NSMutableDictionary *para_value_dic3=[[[NSMutableDictionary alloc]init ] autorelease];
                float  slongRatio3,sshortRatio3;
                int    slongDay3,sshortDay3;
                
                slongRatio3=[[dic3 objectForKey:@"longRatio"] doubleValue];
                sshortRatio3=[[dic3 objectForKey:@"shortRatio"] doubleValue];
                slongDay3=[[dic3 objectForKey:@"longDay"] doubleValue];
                sshortDay3=[[dic3 objectForKey:@"shortDay"] doubleValue];
                
                
                
                [para_value_dic3 setObject:[NSNumber numberWithFloat: slongRatio3] forKey:Para_1];
                [para_value_dic3 setObject:[NSNumber numberWithInt:slongDay3] forKey:Para_2];
                [para_value_dic3 setObject:[NSNumber numberWithFloat:sshortRatio3] forKey:Para_3];
                [para_value_dic3 setObject:[NSNumber numberWithInt:sshortDay3] forKey:Para_4];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic3 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic3 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_LF3 Para_dic:para_value_dic3 period:DWM];
            }
            
            
            
        }
        
        //5.重算資料
        {
            
            //NSLog(@"參數最佳化後，重新計算所有資料");
            //重新計算內存數據
            [self re_calculate_history_indicator_signal];
            
            //報價表更新
            // NSLog(@"最佳化成功 但是尚未完成重新顯示走勢圖或表格 的更新");
            
            
            //公告最佳化個股結束
            {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                
                [dict setObject:self forKey:@"dataobject"];
                
                NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:NOT_sheet_para_optimize_finize
                                  object:self
                                userInfo: dict   ];
                
            }
            
            
            
            
        }
        
        //6.清除每筆計算結果資料
        [optimize_data_dic release];    }
}
-(void)optimize_LFMESA:(NSMutableDictionary *)para_dic{
    
    
    NSLog(@"最佳化：lf");
    //1.取出日期區間
    NSDate *start;
    NSDate *end;
    {
        
        start=[para_dic  objectForKey:Para_Optimize_date_start];
        end=  [para_dic  objectForKey:Para_Optimize_date_end];
        
        
        NSLog(@"開始=%@", start);
        NSLog(@"結束=%@", end );
    }
    
    //2.取出歷史資料
    NSMutableArray *his_dic_serial=[self get_his_data_serial];
    if (his_dic_serial) {
        
        //1.參數
        float longRatio_start,shortRatio_start,periodRatio_start;
        float longRatio_end,shortRatio_end,periodRatio_end;
        float longRatio_step,shortRatio_step,periodRatio_step;
        int   add_limit_start,add_limit_end,add_limit_step;
        
        
        float long_cost,short_cost;//買進與賣出交易成本
        
        
        float Stop_ratio;           //停損率
        int isUse_Stop;             //是否停損
        BOOL  isCreate_Add_Limit_Para; //是否產生加碼參數
        
        int compare_method;
        {
            //技術指標循環參數
            longRatio_start= [[para_dic objectForKey:Para_Default_start_1] floatValue];
            longRatio_end=  [[para_dic objectForKey:Para_Default_end_1] floatValue];
            longRatio_step= [[para_dic objectForKey:Para_Default_step_1] floatValue];
            
            shortRatio_start= [[para_dic objectForKey:Para_Default_start_2] floatValue];
            shortRatio_end=  [[para_dic objectForKey:Para_Default_end_2] floatValue];
            shortRatio_step= [[para_dic objectForKey:Para_Default_step_2] floatValue];
            
            periodRatio_start= [[para_dic objectForKey:Para_Default_start_3] floatValue];
            periodRatio_end=  [[para_dic objectForKey:Para_Default_end_3] floatValue];
            periodRatio_step= [[para_dic objectForKey:Para_Default_step_3] floatValue];
            
            
            add_limit_start= [[para_dic objectForKey:Para_Default_start_4] intValue];
            add_limit_end=  [[para_dic objectForKey:Para_Default_end_4] intValue];
            add_limit_step= [[para_dic objectForKey:Para_Default_step_4] intValue];

            
            //NSLog(@"longRatio_start=%f longRatio_end=%f longRatio_step=%f",longRatio_start,longRatio_end ,longRatio_step);
            
            //比較準則
            compare_method= [[para_dic objectForKey:Para_Optimize_compare_method] intValue];
            
            
            long_cost= [[para_dic objectForKey:Para_Optimize_long_cost] floatValue];
            short_cost= [[para_dic objectForKey:Para_Optimize_short_cost] floatValue];
            
            //停損機制
            isUse_Stop= [[para_dic objectForKey:Para_Optimize_isUse_Stop] intValue];
            Stop_ratio= [[para_dic objectForKey:Para_Optimize_Stop_ratio] floatValue];
        
            //是否產生加碼參數
            isCreate_Add_Limit_Para=[[para_dic objectForKey:Para_Optimize_isCreate_Add_Limit] boolValue];
        
        
        }
        
        //2.進入參數循環
        NSMutableArray *optimize_data_dic=[[NSMutableArray alloc]init]; //儲存每筆計算結果資料
        int count_loop=0; //計數器
        
        for (float longRatio=longRatio_start; longRatio<=longRatio_end; longRatio=longRatio+longRatio_step ) {
             
            for (float shortRatio=shortRatio_start; shortRatio<=shortRatio_end; shortRatio=shortRatio+shortRatio_step ) {
                
                for (float periodRatio=periodRatio_start; periodRatio<=periodRatio_end; periodRatio=periodRatio+periodRatio_step ){
                    
                    for (int add_limit=add_limit_start; add_limit<=add_limit_end; add_limit=add_limit+add_limit_step ){
                    
                        int longDay ;
                        int shortDay ;
                        
                        {
                            
                            NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                            count_loop++;
                            
                            //宣告損益計算變數
                            
                            double last_trade_long_profitratio;         //最後一筆做多獲利率
                            double last_trade_short_profitratio;        //最後一筆做空獲利率
                            
                            
                            double realized_trade_long_profitratio;     //已經實現做多損益
                            double realized_trade_short_profitratio;    //已經實現做空損益
                            double realized_trade_long_profitratio_sum; //已經實現做多損益合計
                            double realized_trade_short_profitratio_sum;//已經實現做空損益合計
                           
                            //double profit_single_realize=0;//單筆已經實現損益 檢查用
                            //double profit_single_unrealize=0;//單筆尚未實現損益 檢查用
                            
                            
                            double long_total_count; //做多交易次數
                            double long_win_count;   //做多交易賺錢次數
                            double long_win_ratio;   //做多勝率
                            
                            double short_total_count; //做空交易次數
                            double short_win_count;   //做空交易賺錢次數
                            double short_win_ratio;   //做空勝率
                            
                            double ls_total_count; //多空交易次數
                            double ls_win_count;   //多空交易賺錢次數
                            double ls_win_ratio;   //多空勝率
                            
                            double long_max_gain; //做多最大獲利率
                            double long_max_loss; //做多最大虧損率
                            double short_max_gain; //做空最大獲利率
                            double short_max_loss; //做空最大虧損率
                            double ls_max_gain;  //多空最大獲利率
                            double ls_max_loss; //多空最大虧損率
                            
                            double year; //開始計算日期
                            
                            double return_long;// 作多年化報酬率
                            double return_short;// 作空年化報酬率
                            double return_ls;// 作空年化報酬率
                            {
                                
                                last_trade_long_profitratio=0;
                                last_trade_short_profitratio=0;
                                
                                
                                realized_trade_long_profitratio_sum=0;
                                realized_trade_short_profitratio_sum=0;
                                
                                long_total_count=0;
                                long_win_count=0;
                                long_win_ratio=0;
                                
                                short_total_count=0;
                                short_win_count=0;
                                short_win_ratio=0;
                                
                                ls_total_count=0;
                                ls_win_count=0;
                                ls_win_ratio=0;
                                
                                long_max_gain=0; //做多最大獲利率
                                long_max_loss=0; //做多最大虧損率
                                short_max_gain=0; //做空最大獲利率
                                short_max_loss=0; //做空最大虧損率
                                ls_max_gain=0;  //多空最大獲利率
                                ls_max_loss=0; //多空最大虧損率
                                
                                year=0;
                                
                                return_long=0;
                                return_short=0;
                                return_ls=0;
                                
                            }
                            
                            //a.進入每筆最佳化計算
                            for (int i=0 ; i<[his_dic_serial count]; i++) {
                                
                                
                                NSMutableDictionary *his_dic =[his_data_serial objectAtIndex:i];
                                
                                NSDate *now=[his_dic objectForKey:HIS_basic_date];
                                
                                
                                //判斷區間內
                                if ([now compare:start]==NSOrderedDescending  && [now compare:end]==NSOrderedAscending) {
                                    
                                    //正式進入計算
                                    
                                    //建立 計算暫存記憶體空間
                                    NSMutableDictionary *temp_cal=[[NSMutableDictionary alloc] init];
                                    
                                    [his_dic setObject:temp_cal forKey:HIS_optimize_temp];
                                    
                                    [temp_cal release];
                                    
                                    //開始計算
                                    {
                                        
                                        //移動均線
                                        float ma_fast,ma_slow;
                                        BOOL fastCrossSlow;
                                        BOOL isRealFisrtEnter=NO; //是否第一次進場
                                        
                                        {
                                            ma_fast= 0;
                                            ma_slow= 0;
                                            
                                            
                                            //如果有前期的判斷值就用前一期的判斷值
                                            
                                            
                                            if ([self get_his_temp_optimize_NSNumber:HIS_dic_temp_MA_fastCrossSlow i:i-1  historyData: his_dic_serial ]  ) {
                                                
                                                fastCrossSlow=[[self get_his_temp_optimize_NSNumber:HIS_dic_temp_MA_fastCrossSlow i:i-1  historyData: his_dic_serial ] boolValue];
                                            }
                                            else{
                                                
                                                fastCrossSlow=NO;
                                                
                                            }
                                            
                                            //判斷均線是否交叉
                                            {
                                                //只有在均線尚未出現交叉訊號之前 才需要計算均線
                                                if (fastCrossSlow==NO) {
                                                    
                                                    
                                                    int ma_period_short=10;
                                                    int ma_period_long=20;
                                                    
                                                    //限制移動均線的週期
                                                    if (i>ma_period_long) {
                                                        
                                                        float sumfast=0;
                                                        float sumslow=0;
                                                        
                                                        for (int is=0; is<ma_period_short;is++ ) {
                                                            
                                                            
                                                            double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                                                            sumfast=sumfast+close;
                                                        }
                                                        
                                                        
                                                        for (int is=0; is<ma_period_long;is++ ) {
                                                            
                                                            double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                                                            sumslow=sumslow+close;
                                                        }
                                                        
                                                        //移動均線值
                                                        ma_fast=sumfast/ma_period_short;
                                                        ma_slow=sumslow/ma_period_long;
                                                        
                                                        //前一期移動均線值
                                                        
                                                        float ma_fast_1= [self get_his_temp_optimize_value:HIS_dic_temp_MA_Fast i:i-1 historyData:his_dic_serial];
                                                        
                                                        float ma_slow_1= [self get_his_temp_optimize_value:HIS_dic_temp_MA_Slow i:i-1 historyData:his_dic_serial];
                                                        
                                                        //判斷短天期均線是否穿越長天期均線
                                                        if (ma_fast>ma_slow && ma_fast_1<ma_slow_1) {
                                                            fastCrossSlow=YES;
                                                            isRealFisrtEnter=YES;
                                                            
                                                        }
                                                        
                                                        
                                                        
                                                        
                                                    }
                                                }
                                                
                                                
                                                
                                                
                                                
                                                
                                            }
                                        }
                                        
                                        //0.period
                                        double Smooth,price,Detrender,Period,Q1,l1,jl,jQ,l2,Q2,Re,lm,SmoothPeriod,Phase,DeltaPhase;
                                        
                                        {
                                            //1.開高收低 基本每筆資料
                                            double  high,low,open  ;
                                            double  close;
                                            {
                                                //調整收盤價比率
                                                double adj_ratio;
                                                {
                                                    double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
                                                    double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                                                    
                                                    
                                                    if (isUseAdjClose==YES) {
                                                        adj_ratio=adj_close/close;
                                                    }
                                                    else{
                                                        adj_ratio=1;
                                                    }
                                                }
                                                
                                                
                                                
                                                
                                                high=[[his_dic objectForKey:HIS_basic_high] doubleValue]* adj_ratio;
                                                low=[[his_dic objectForKey:HIS_basic_low] doubleValue]* adj_ratio;
                                                open=[[his_dic objectForKey:HIS_basic_open] doubleValue]* adj_ratio;
                                                close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
                                                
                                            }
                                            
                                            //2.計算用的變數
                                            
                                            
                                            //3.計算MESA
                                            {
                                                price =(high +low)/2;
                                                
                                                
                                                Smooth =(4 * price + 3 *[self get_his_temp_optimize_value:HIS_dic_temp_price  i:i-1 historyData:his_dic_serial]  + 2 * [self get_his_temp_optimize_value:HIS_dic_temp_price  i:i-2 historyData:his_dic_serial] + [self get_his_temp_optimize_value:HIS_dic_temp_price  i:i-3 historyData:his_dic_serial])/10;
                                                
                                                Detrender=(0.0962*Smooth+0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-2 historyData:his_dic_serial] -0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-4 historyData:his_dic_serial]-0.0962*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54);
                                                
                                                Q1 =(0.0962*Detrender +0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-2 historyData:his_dic_serial]-0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-4 historyData:his_dic_serial]-0.0962*[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54);
                                                
                                                l1 =[self get_his_temp_optimize_value:HIS_dic_temp_Detrender  i:i-3 historyData:his_dic_serial];
                                                jl=(0.0962*l1+0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_l1  i:i-2 historyData:his_dic_serial]-0.5769*[self get_his_temp_optimize_value:HIS_dic_temp_l1  i:i-4 historyData:his_dic_serial]-.0962*[self get_his_temp_optimize_value:HIS_dic_temp_l1  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54);
                                                
                                                jQ=(0.0962*Q1+.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Q1  i:i-2 historyData:his_dic_serial]-.5769*[self get_his_temp_optimize_value:HIS_dic_temp_Q1  i:i-4 historyData:his_dic_serial]-0.0962*[self get_his_temp_optimize_value:HIS_dic_temp_Q1  i:i-6 historyData:his_dic_serial])*(0.075*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial]+0.54) ;
                                                
                                                l2=l1-jQ;
                                                Q2=Q1+jl;
                                                
                                                l2=0.2*l2 +0.8*[self get_his_temp_optimize_value:HIS_dic_temp_l2  i:i-1 historyData:his_dic_serial];
                                                Q2=0.2*Q2+0.8*[self get_his_temp_optimize_value:HIS_dic_temp_Q2  i:i-1 historyData:his_dic_serial];
                                                
                                                Re =l2 *[self get_his_temp_optimize_value:HIS_dic_temp_l2  i:i-1 historyData:his_dic_serial]+Q2*[self get_his_temp_optimize_value:HIS_dic_temp_Q2  i:i-1 historyData:his_dic_serial];
                                                lm=l2*[self get_his_temp_optimize_value:HIS_dic_temp_Q2  i:i-1 historyData:his_dic_serial]-Q2*[self get_his_temp_optimize_value:HIS_dic_temp_l2  i:i-1 historyData:his_dic_serial];
                                                
                                                Re =0.2*Re +0.8*[self get_his_temp_optimize_value:HIS_dic_temp_Re  i:i-1 historyData:his_dic_serial];
                                                lm=0.2*lm+0.8*[self get_his_temp_optimize_value:HIS_dic_temp_lm  i:i-1 historyData:his_dic_serial];
                                                
                                                
                                                if( lm  !=0 && Re !=0 )
                                                {
                                                    Period = 360/(atan((lm /Re ))*180/(4*atan(1)));
                                                    
                                                }
                                                else {
                                                    Period=0;
                                                }
                                                if( Period >1.5*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial])
                                                    Period =1.5*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial];
                                                
                                                if(Period <0.67*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial])
                                                    Period =0.67*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial];
                                                
                                                
                                                if(Period <6)
                                                    Period =6;
                                                if(Period >50)
                                                    Period =50;
                                                
                                                Period =0.2*Period +0.8*[self get_his_temp_optimize_value:HIS_dic_temp_Period  i:i-1 historyData:his_dic_serial];
                                                
                                                
                                                SmoothPeriod =0.33*Period +0.67*[self get_his_temp_optimize_value:HIS_dic_temp_Smooth  i:i-1 historyData:his_dic_serial];
                                                
                                                if( l1  !=0 ){
                                                    Phase =atan(Q1 /l1 )*180/(4*atan(1));
                                                }
                                                else{
                                                    Phase=0;
                                                }
                                                
                                                DeltaPhase=[self get_his_temp_optimize_value:HIS_dic_temp_Phase  i:i-1 historyData:his_dic_serial] - Phase ;
                                                
                                                if(DeltaPhase <1)
                                                    DeltaPhase =1;
                                                
                                            }
                                            
                                            
                                        }
                                        
                                        //週期
                                       
                                        
                                        
                                        if ((int)(Period *periodRatio)) {
                                            longDay=(int)(Period *periodRatio);
                                            shortDay=(int)(Period *periodRatio);
                                        }
                                        else{
                                            longDay    =1;
                                            shortDay   =1;
                                        }

                                        
                                        
                                        
                                        
                                        
                                        if (longDay<1) {
                                            longDay=1;
                                        }
                                        if (shortDay<1) {
                                            shortDay=1;
                                        }
                                        
                                        //1.開高收低 基本每筆資料
                                        double   open;
                                        double  close;
                                        NSDate  *dates;
                                        {
                                            //調整收盤價比率
                                            double adj_ratio;
                                            {
                                                double adj_close=[[his_dic objectForKey:HIS_basic_adjclose] doubleValue ];
                                                double close=    [[his_dic objectForKey:HIS_basic_close ] doubleValue ];
                                                dates=[his_dic objectForKey:HIS_basic_date];
                                                //  NSLog(@"dates=%@ %i",dates,fastCrossSlow);
                                                
                                                
                                                if (isUseAdjClose==YES) {
                                                    adj_ratio=adj_close/close;
                                                }
                                                else{
                                                    adj_ratio=1;
                                                }
                                            }
                                            
                                            
                                            open=[[his_dic objectForKey:HIS_basic_open] doubleValue]* adj_ratio;
                                            close=[[his_dic objectForKey:HIS_basic_close] doubleValue]* adj_ratio;
                                            
                                        }
                                        
                                        
                                        //2.計算用的變數
                                        float LF_bout;
                                        float LF_sout;
                                        int LF_b;
                                        int LF_s;
                                        int LF_b_1;
                                        int LF_s_1;
                                        
                                        int long_step_count;
                                        int short_step_count;
                                        BOOL isAdd_long_step_count=NO; //是否有做多加碼
                                        BOOL isAdd_short_step_count=NO;//是否有做空加碼
                                        
                                        
                                        //3.計算LF
                                        {
                                            
                                            if (i>=1) {
                                                LF_bout= [self get_his_temp_optimize_value:HIS_dic_temp_LF_bout i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_sout= [self get_his_temp_optimize_value:HIS_dic_temp_LF_sout i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_b=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_b i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_s=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_s i:i-1 historyData:his_dic_serial] ;
                                                
                                                //紀錄上一期
                                                LF_b_1=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_b i:i-1 historyData:his_dic_serial] ;
                                                
                                                LF_s_1=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LF_s i:i-1 historyData:his_dic_serial] ;
                                                
                                                
                                                //摺疊次數
                                                long_step_count=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LFMESA_long_step_count i:i-1 historyData:his_dic_serial] ;
                                                
                                               
                                                
                                                short_step_count=(int) [self get_his_temp_optimize_value:HIS_dic_temp_LFMESA_short_step_cpont i:i-1 historyData:his_dic_serial] ;
                                               
                                                
                                                
                                                
                                            }
                                            else{
                                                LF_bout=0;
                                                LF_sout=0;
                                                LF_b=0;
                                                LF_s=0;
                                                LF_b_1=0;
                                                LF_s_1=0;
                                                
                                                long_step_count=0;
                                                short_step_count=0;
                                                
                                            }
                                            
                                            int start_i;
                                            {
                                                if (longDay>shortDay) {
                                                    start_i=longDay;
                                                }
                                                else{
                                                    start_i=shortDay;
                                                }
                                                
                                                
                                            }
                                            
                                            //做多區間
                                            float BRange;
                                            {
                                                float rhigh=0;
                                                float rlow=0;
                                                {
                                                    //區間最大值
                                                    for (int Hi=0;Hi<longDay ; Hi++) {
                                                        
                                                        if (Hi==0) {
                                                            
                                                            rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                        }
                                                        else{
                                                            if (i-Hi >=0 && i-Hi <[his_dic_serial count] ) {
                                                                
                                                                if (rhigh<[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                                                    
                                                                    rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                                    
                                                                }
                                                                
                                                                
                                                            }
                                                            
                                                            
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    //區間最小值
                                                    for (int Li=0;Li<longDay ; Li++) {
                                                        
                                                        if (Li==0) {
                                                            
                                                            rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                        }
                                                        else{
                                                            
                                                            if (i-Li >=0 && i-Li <[his_dic_serial count] ) {
                                                                
                                                                if (rlow>[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                                                    
                                                                    rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                                    
                                                                }
                                                                
                                                                
                                                            }
                                                            
                                                            
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    
                                                    
                                                }
                                                BRange=rhigh-rlow;
                                            }
                                            
                                            //做空區間
                                            float SRange;
                                            {
                                                float rhigh=0;
                                                float rlow=0;
                                                {
                                                    //區間最大值
                                                    for (int Hi=0;Hi<shortDay ; Hi++) {
                                                        
                                                        if (Hi==0) {
                                                            
                                                            rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                        }
                                                        else{
                                                            if (i-Hi >=0 && i-Hi <[his_dic_serial count] ) {
                                                                
                                                                if (rhigh<[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue]) {
                                                                    
                                                                    rhigh=[[[his_dic_serial objectAtIndex:i-Hi] objectForKey:HIS_basic_high] doubleValue];
                                                                    
                                                                }
                                                            }
                                                            
                                                            
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    //區間最小值
                                                    for (int Li=0;Li<shortDay ; Li++) {
                                                        
                                                        if (Li==0) {
                                                            
                                                            rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                        }
                                                        else{
                                                            
                                                            if (i-Li >=0 && i-Li <[his_dic_serial count] ) {
                                                                
                                                                if (rlow>[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue]) {
                                                                    
                                                                    rlow=[[[his_dic_serial objectAtIndex:i-Li] objectForKey:HIS_basic_low] doubleValue];
                                                                    
                                                                }
                                                                
                                                                
                                                                
                                                            }
                                                            
                                                            
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    
                                                }
                                                
                                                SRange=rhigh-rlow;
                                            }
                                            
                                            
                                            {
                                                
                                                float close=[[[his_dic_serial objectAtIndex:i] objectForKey:HIS_basic_adjclose] doubleValue];
                                                
                                                if (LF_b==0 && LF_s==0 && fastCrossSlow==YES ) {
                                                    LF_b=1;
                                                    LF_s=0;
                                                    LF_bout=close-BRange*longRatio;
                                                    LF_sout=0;
                                                    
                                                    long_step_count=1;
                                                    short_step_count=0;
                                                    
                                                    
                                                }
                                                else if (LF_b==1 && LF_bout+BRange<close) {
                                                    
                                                    LF_bout=LF_bout+BRange*longRatio;
                                                    
                                                    
                                                    //限制做多加碼上限
                                                    if (add_limit > long_step_count) {
                                                        
                                                        long_step_count=long_step_count+1;
                                                        isAdd_long_step_count=YES;
                                                        
                                                    }

                                                }
                                                else if (LF_b==1 && close<LF_bout) {
                                                    LF_b=0;
                                                    LF_s=1;
                                                    LF_sout=close+SRange*shortRatio;
                                                    LF_bout=0;
                                                    
                                                    long_step_count=0;
                                                    short_step_count=1;
                                                    
                                                }
                                                else if (LF_s==1 && LF_sout-SRange>close) {
                                                    LF_sout=LF_sout-SRange*shortRatio;
                                                    
                                                    //限制做空加碼上限
                                                    if (add_limit > short_step_count) {
                                                        
                                                        short_step_count=short_step_count+1;
                                                        isAdd_short_step_count=YES;
                                                    }

                                                }
                                                else if (LF_s==1 && close>LF_sout) {
                                                    LF_s=0;
                                                    LF_b=1;
                                                    LF_bout=close-BRange*longRatio;
                                                    LF_sout=0;
                                                    
                                                    
                                                    long_step_count=1;
                                                    short_step_count=0;
                                                    
                                                }
                                                
                                                
                                                
                                            }
                                            
                                            
                                        }
                                        
                                        //4.訊號判斷
                                        int BuyOrSell;      //此位置 i 是否要買或賣
                                        int Position_State; //此位置 i 多空狀態
                                        int BS_Stop; //停損機制 2表示做空停損 -2表示做多停損
                                        {
                                            BuyOrSell=0;
                                            Position_State=0;
                                            BS_Stop=0;
                                            
                                            if (i>0) {
                                                
                                                //買賣訊號
                                                if (LF_b_1==1 && LF_s==1) {
                                                    BuyOrSell=-1;
                                                    
                                                }
                                                else if ((LF_s_1==1 && LF_b==1) ||  isRealFisrtEnter==YES) {
                                                    BuyOrSell=1;
                                                }
                                                else {
                                                    BuyOrSell=0;
                                                }
                                                
                                                //狀態
                                                if (LF_s==1) {
                                                    Position_State=-1;
                                                }
                                                else {
                                                    Position_State=1;
                                                }
                                                
                                                
                                            }
                                            
                                            
                                        }
                                        
                                        
                                        //6.損益部位
                                        
                                        
                                        int BS_last ;// 最後一期買賣方向 因為是以隔天開盤價作為當期買賣價位
                                        double enter_price; //最後一期買進場價位
                                        double enter_price_average; //平均買進場價位
                                        double profit_single_realize=0;//單筆已經實現損益 檢查用
                                        double profit_single_unrealize=0;//單筆尚未實現損益 檢查用
                                        
                                        {
                                            //變數歸0
                                            {
                                                last_trade_long_profitratio=0;
                                                last_trade_short_profitratio=0;
                                                
                                                realized_trade_long_profitratio=0;
                                                realized_trade_short_profitratio=0;
                                                
                                                realized_trade_long_profitratio_sum=0;
                                                realized_trade_short_profitratio_sum=0;
                                                
                                                long_total_count=0;
                                                long_win_count=0;
                                                long_win_ratio=0;
                                                
                                                short_total_count=0;
                                                short_win_count=0;
                                                short_win_ratio=0;
                                                
                                                ls_total_count=0;
                                                ls_win_count=0;
                                                ls_win_ratio=0;
                                                
                                                long_max_gain=0; //做多最大獲利率
                                                long_max_loss=0; //做多最大虧損率
                                                short_max_gain=0; //做空最大獲利率
                                                short_max_loss=0; //做空最大虧損率
                                                ls_max_gain=0;  //多空最大獲利率
                                                ls_max_loss=0; //多空最大虧損率
                                                
                                                
                                                BS_last=0;
                                                enter_price=0;
                                                enter_price_average=0;
                                                
                                                year=0;
                                                
                                                return_long=0;
                                                return_short=0;
                                                return_ls=0;
                                            }
                                            
                                            if (i>0) {
                                                
                                                
                                                int BS_1 ;// 前一期買賣動作方向 因為是以隔天開盤價作為當期買賣價位
                                                
                                                //停損機制 最佳化
                                                int BS_Stop_1; //前一期是否有出現停損動作
                                                //BS_Stop_1=0;
                                                
                                                //1.取出前一期的資料
                                                NSMutableDictionary *his_dic_1=[his_data_serial objectAtIndex:i-1];//前一筆
                                                NSMutableDictionary *his_dic_0=[his_data_serial objectAtIndex:0];  //第0筆
                                                
                                                
                                                {
                                                    
                                                    //停損機制 最佳化
                                                    //前一期是否有出現停損動作
                                                    BS_Stop_1=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_signal_LF_BS_Stop] intValue];
                                                    
                                                    
                                                    //前一期 買賣動作方向
                                                    BS_1=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_signal_LF_BS] intValue];
                                                    
                                                    
                                                    
                                                    //前一期 已經實現做多合計
                                                    realized_trade_long_profitratio_sum=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_longratio_realizedtrade_temp] doubleValue];
                                                    
                                                    
                                                    
                                                    //前一期 已經實現做空合計
                                                    realized_trade_short_profitratio_sum=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_shortratio_realizedtrade_temp] doubleValue];
                                                    
                                                    //前一期 做多交易次數
                                                    long_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_total_count_temp] doubleValue];
                                                    
                                                    //前一期 做多賺錢交易次數
                                                    long_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_win_count_temp] doubleValue];
                                                    
                                                    //前一期 做多勝率
                                                    long_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_win_ratio_temp] doubleValue];
                                                    
                                                    
                                                    //前一期 做空交易次數
                                                    short_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_total_count_temp] doubleValue];
                                                    
                                                    //前一期 做空賺錢交易次數
                                                    short_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_win_count_temp] doubleValue];
                                                    
                                                    //前一期 做空勝率
                                                    short_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_win_ratio_temp] doubleValue];
                                                    
                                                    
                                                    //前一期 多空交易次數
                                                    ls_total_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_total_count_temp] doubleValue];
                                                    
                                                    //前一期 多空賺錢交易次數
                                                    ls_win_count=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_win_count_temp] doubleValue];
                                                    
                                                    //前一期 多空勝率
                                                    ls_win_ratio=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_win_ratio_temp] doubleValue];
                                                    
                                                    //做多最大獲利率
                                                    long_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_max_gain_temp] doubleValue];
                                                    
                                                    //做多最大虧損率
                                                    long_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_long_max_loss_temp] doubleValue];
                                                    
                                                    //做空最大獲利率
                                                    short_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_max_gain_temp] doubleValue];
                                                    
                                                    //做空最大虧損率
                                                    short_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_short_max_loss_temp] doubleValue];
                                                    
                                                    //多空最大獲利率
                                                    ls_max_gain=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_max_gain_temp] doubleValue];
                                                    
                                                    //多空最大虧損率
                                                    ls_max_loss=[[[his_dic_1 objectForKey:HIS_optimize_temp]  objectForKey:CL_his_data_profit_LF_LS_max_loss_temp] doubleValue];
                                                    
                                                    
                                                    
                                                    
                                                }
                                                
                                                
                                                //2.判斷上一期是否有買賣動作
                                                if (BS_1==0) {
                                                    
                                                    enter_price=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice  i:i-1 historyData:his_dic_serial] ;
                                                    
                                                    //平均進場成本
                                                    {
                                                        
                                                        //前一期是否有加碼
                                                        BOOL isLong_Add_1=[[self get_his_temp_optimize_NSNumber:HIS_dic_temp_profit_long_add  i:i-1 historyData:his_dic_serial] boolValue];
                                                        
                                                        
                                                        BOOL isShort_Add_1=[[self get_his_temp_optimize_NSNumber:HIS_dic_temp_profit_short_add  i:i-1 historyData:his_dic_serial] boolValue];
                                                        
                                                        
                                                        
                                                        if (isLong_Add_1==YES || isShort_Add_1==YES) {
                                                            
                                                            //上次進場平均成本HIS_dic_temp_profit_enterprice_average
                                                            enter_price_average=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice_average  i:i-1 historyData:his_dic_serial];
                                                            
                                                            //做多
                                                            {
                                                                int long_position_1=(int) [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial];
                                                                
                                                                //long_step_count_1=long_step_count_1 ; //尚未加碼前的數字
                                                                
                                                                if (isLong_Add_1==YES) {
                                                                    
                                                                    enter_price_average=(enter_price_average* long_position_1 +open)/(long_position_1+1);
                                                                }
                                                                
                                                                
                                                                
                                                            }
                                                            //做空
                                                            {
                                                                
                                                                int short_position_1=(int) [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs i:i-1 historyData:his_dic_serial];
                                                                
                                                                short_position_1=short_position_1*-1;
                                                                
                                                                if (isShort_Add_1==YES) {
                                                                    
                                                                    enter_price_average=(enter_price_average* short_position_1 +open)/(short_position_1+1);
                                                                }
                                                                
                                                                
                                                                
                                                                
                                                            }
                                                            
                                                            
                                                            
                                                            
                                                        }
                                                        else{
                                                            
                                                            enter_price_average=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice_average  i:i-1 historyData:his_dic_serial];
                                                        }
                                                        
                                                        
                                                        
                                                    }
                                                    
                                                    
                                                    
                                                    
                                                    //停損機制 最佳化
                                                    //前一期是否需要停損
                                                    if (BS_Stop_1==-2 ) {
                                                        
                                                        //NSLog(@"BS_Stop_1==-2");
                                                        
                                                        //前一期出現需要做多停損訊號
                                                        BS_last=0;
                                                        //作多出場損益
                                                        {
                                                            //做多最近一筆 含有交易成本
                                                            realized_trade_long_profitratio=(open-enter_price)/enter_price*100-(long_cost+short_cost)*100;
                                                            
                                                            
                                                            float enter_price_average_1=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice_average  i:i-1 historyData:his_dic_serial];
                                                            
                                                            
                                                            float  BS_position_1=  [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial] ;
                                                            
                                                            //部位調整比率用再做資金分配
                                                            float adjRatio_Position=   BS_position_1/  add_limit ;
                                                            if (adjRatio_Position<0) {
                                                                adjRatio_Position=adjRatio_Position*-1;
                                                            }
                                                            
                                                            
                                                            profit_single_realize=((open-enter_price_average_1)/enter_price_average_1*100-(long_cost+short_cost)*100)*adjRatio_Position;
                                                            
                                                            realized_trade_long_profitratio=profit_single_realize;
                                                            
                                                            
                                                            
                                                            //累計做多
                                                            realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                                                            
                                                            //累計做多交易次數
                                                            long_total_count=long_total_count+1;
                                                            
                                                            //做多交易賺錢次數
                                                            if (realized_trade_long_profitratio>0) {
                                                                //賺錢才可以+1
                                                                long_win_count=long_win_count+1;
                                                            }
                                                            else{
                                                                long_win_count=long_win_count;
                                                            }
                                                            
                                                            //勝率
                                                            if (long_total_count>0) {
                                                                long_win_ratio= long_win_count/long_total_count*100;
                                                            }
                                                            else{
                                                                long_win_ratio=0;
                                                            }
                                                            
                                                            //做多最大獲利
                                                            if (realized_trade_long_profitratio>long_max_gain) {
                                                                long_max_gain=realized_trade_long_profitratio;
                                                            }
                                                            
                                                            //做多最大損失
                                                            if (realized_trade_long_profitratio<long_max_loss) {
                                                                long_max_loss=realized_trade_long_profitratio;
                                                            }
                                                            
                                                            
                                                        }
                                                        
                                                    }
                                                    else if (BS_Stop_1==2 ){
                                                        //前一期出現做空需要停損的訊號
                                                        BS_last=0;
                                                        //作空出場損益
                                                        {
                                                            //做空最近一筆 含有交易成本
                                                            realized_trade_short_profitratio=(enter_price-open)/enter_price*100-(long_cost+short_cost)*100;
                                                            
                                                            float enter_price_average_1=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice_average  i:i-1 historyData:his_data_serial];
                                                            
                                                            float  BS_position_1=  [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_data_serial] ;
                                                            
                                                            //部位調整比率用再做資金分配
                                                            float adjRatio_Position=   BS_position_1/  add_limit ;
                                                            if (adjRatio_Position<0) {
                                                                adjRatio_Position=adjRatio_Position*-1;
                                                            }
                                                            
                                                            
                                                            
                                                            profit_single_realize=((open-enter_price_average_1)*-1/enter_price_average_1*100-(long_cost+short_cost)*100)*adjRatio_Position;
                                                            
                                                            realized_trade_short_profitratio=profit_single_realize;
                                                           
                                                            
                                                            
                                                            //累計做多
                                                            realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                                                            
                                                            
                                                            //累計做空交易次數
                                                            short_total_count=short_total_count+1;
                                                            
                                                            
                                                            //做空交易賺錢次數
                                                            if (realized_trade_short_profitratio>0) {
                                                                //賺錢才可以+1
                                                                short_win_count=short_win_count+1;
                                                            }
                                                            else{
                                                                short_win_count=short_win_count;
                                                            }
                                                            
                                                            //勝率
                                                            if (short_total_count>0) {
                                                                short_win_ratio= short_win_count/short_total_count*100;
                                                            }
                                                            else{
                                                                short_win_ratio=0;
                                                            }
                                                            
                                                            
                                                            //做空最大獲利
                                                            if (realized_trade_short_profitratio>short_max_gain) {
                                                                short_max_gain=realized_trade_short_profitratio;
                                                            }
                                                            
                                                            //做空最大損失
                                                            if (realized_trade_short_profitratio<short_max_loss) {
                                                                short_max_loss=realized_trade_short_profitratio;
                                                            }
                                                        }
                                                        
                                                    }
                                                    else{
                                                        /*
                                                         if (enter_price==0) {
                                                         NSLog(@"slow=%f fast=%f",SlowLim,FastLim);
                                                         }
                                                         */
                                                        
                                                        //表示上一期無買賣動作
                                                        
                                                        //取出最後一筆的狀態 在轉移到下一期
                                                        BS_last=[self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial] ;
                                                        
                                                        
                                                        BOOL isAdd_long_step_count_1= [[self get_his_temp_optimize_NSNumber: HIS_dic_temp_profit_long_add  i:i-1 historyData:his_dic_serial] boolValue];
                                                        
                                                        //考慮加碼來增加多方或是空方部位
                                                        if (isAdd_long_step_count_1==YES) {
                                                            
                                                            if (BS_last>0) {
                                                                
                                                                //表示是有多單部位狀態才可以加多
                                                                BS_last=BS_last+1;
                                                            }
                                                            
                                                        }
                                                        
                                                        
                                                        BOOL isAdd_short_step_count_1= [[self get_his_temp_optimize_NSNumber: HIS_dic_temp_profit_short_add   i:i-1 historyData:his_dic_serial] boolValue];
                                                        
                                                        
                                                        if (isAdd_short_step_count_1==YES) {
                                                            
                                                            if (BS_last<0) {
                                                                //表示是有空頭部位的情況下才加空
                                                                BS_last=BS_last-1;
                                                            }
                                                            
                                                            
                                                            
                                                        }

                                                        
                                                        
                                                    }
                                                    
                                                    
                                                }
                                                else{
                                                    //表示上一期有買賣動作
                                                    
                                                    //1.計算已經實現損益
                                                    {
                                                        //上一期尚未動作之前的部位
                                                        int BS_last_unchange;        //上一期的部位方向
                                                        double enterprice_last_unchange;//上一期的部位的進場價格還尚未更新到本期的開盤價之前的資料
                                                        
                                                        BS_last_unchange=[self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial];
                                                       
                                                        enterprice_last_unchange=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice  i:i-1 historyData:his_dic_serial];
                                                        
                                                        
                                                         int iBS_position_1=  [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_dic_serial] ;
                                                        
                                                        //計算已經實現損益與累計實現損益
                                                        if (iBS_position_1>0) {
                                                            
                                                            
                                                            
                                                            float  BS_position_1=  [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_data_serial] ;
                                                            
                                                            //部位調整比率用再做資金分配
                                                            float adjRatio_Position=   BS_position_1/  add_limit ;
                                                            if (adjRatio_Position<0) {
                                                                adjRatio_Position=adjRatio_Position*-1;
                                                            }
                                                            
                                                            
                                                            
                                                            float enter_price_average_1=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice_average  i:i-1 historyData:his_data_serial];
                                                            
                                                            
                                                            profit_single_realize=((open-enter_price_average_1)/enter_price_average_1*100-(long_cost+short_cost)*100)*adjRatio_Position;
                                                            
                                                            
                                                            realized_trade_long_profitratio=profit_single_realize;
                                                            
                                                           
                                                            
                                                            //NSLog(@"做多 出場%@ o=%f e=%f p=%f",dates, open,enterprice_last_unchange,open-enterprice_last_unchange);
                                                            
                                                            
                                                            //累計做多
                                                            realized_trade_long_profitratio_sum=realized_trade_long_profitratio_sum+ realized_trade_long_profitratio;
                                                            
                                                            //累計做多交易次數
                                                            long_total_count=long_total_count+1;
                                                            
                                                            //做多交易賺錢次數
                                                            if (realized_trade_long_profitratio>0) {
                                                                //賺錢才可以+1
                                                                long_win_count=long_win_count+1;
                                                            }
                                                            else{
                                                                long_win_count=long_win_count;
                                                            }
                                                            
                                                            //勝率
                                                            if (long_total_count>0) {
                                                                long_win_ratio= long_win_count/long_total_count*100;
                                                            }
                                                            else{
                                                                long_win_ratio=0;
                                                            }
                                                            
                                                            //做多最大獲利
                                                            if (realized_trade_long_profitratio>long_max_gain) {
                                                                long_max_gain=realized_trade_long_profitratio;
                                                            }
                                                            
                                                            //做多最大損失
                                                            if (realized_trade_long_profitratio<long_max_loss) {
                                                                long_max_loss=realized_trade_long_profitratio;
                                                            }
                                                            
                                                            
                                                        }
                                                        else if (iBS_position_1<0){
                                                            //做空最近一筆 含有交易成本
                                                            //realized_trade_short_profitratio=(enterprice_last_unchange-open)/enterprice_last_unchange*100-(long_cost+short_cost)*100;
                                                            
                                                            float  BS_position_1=  [self get_his_temp_optimize_value:HIS_dic_temp_profit_bs  i:i-1 historyData:his_data_serial] ;
                                                            
                                                            //部位調整比率用再做資金分配
                                                            float adjRatio_Position=   BS_position_1/  add_limit ;
                                                            if (adjRatio_Position<0) {
                                                                adjRatio_Position=adjRatio_Position*-1;
                                                            }
                                                            
                                                            
                                                            
                                                            
                                                            float enter_price_average_1=[self get_his_temp_optimize_value:HIS_dic_temp_profit_enterprice_average  i:i-1 historyData:his_data_serial];
                                                            
                                                            
                                                            profit_single_realize=((open-enter_price_average_1)*-1/enter_price_average_1*100-(long_cost+short_cost)*100 )*adjRatio_Position;
                                                            
                                                            
                                                            realized_trade_short_profitratio=profit_single_realize;
                                                            
                                                            
                                                            
                                                            //累計做多
                                                            realized_trade_short_profitratio_sum=realized_trade_short_profitratio_sum+ realized_trade_short_profitratio;
                                                            
                                                            
                                                            //累計做空交易次數
                                                            short_total_count=short_total_count+1;
                                                            
                                                            
                                                            //做空交易賺錢次數
                                                            if (realized_trade_short_profitratio>0) {
                                                                //賺錢才可以+1
                                                                short_win_count=short_win_count+1;
                                                            }
                                                            else{
                                                                short_win_count=short_win_count;
                                                            }
                                                            
                                                            //勝率
                                                            if (short_total_count>0) {
                                                                short_win_ratio= short_win_count/short_total_count*100;
                                                            }
                                                            else{
                                                                short_win_ratio=0;
                                                            }
                                                            
                                                            
                                                            //做空最大獲利
                                                            if (realized_trade_short_profitratio>short_max_gain) {
                                                                short_max_gain=realized_trade_short_profitratio;
                                                            }
                                                            
                                                            //做空最大損失
                                                            if (realized_trade_short_profitratio<short_max_loss) {
                                                                short_max_loss=realized_trade_short_profitratio;
                                                            }
                                                            
                                                            
                                                            
                                                        }
                                                        
                                                        //多空合計
                                                        ls_total_count=long_total_count+short_total_count;
                                                        ls_win_count=long_win_count+short_win_count;
                                                        
                                                        if (ls_total_count>0) {
                                                            ls_win_ratio=ls_win_count/ls_total_count*100;
                                                        }
                                                        else{
                                                            ls_win_ratio=0;
                                                        }
                                                        
                                                        //多空最大獲利
                                                        if (realized_trade_long_profitratio>ls_max_gain) {
                                                            ls_max_gain=realized_trade_long_profitratio;
                                                        }
                                                        if (realized_trade_short_profitratio>ls_max_gain) {
                                                            ls_max_gain=realized_trade_short_profitratio;
                                                        }
                                                        //多空最大損失
                                                        if (realized_trade_long_profitratio<ls_max_loss) {
                                                            ls_max_loss=realized_trade_long_profitratio;
                                                        }
                                                        if (realized_trade_short_profitratio<ls_max_loss) {
                                                            ls_max_loss=realized_trade_short_profitratio;
                                                        }
                                                    }
                                                    
                                                    //2.更新最新資料
                                                    BS_last=BS_1;
                                                    enter_price=open;
                                                    enter_price_average=open;
                                                    
                                                }
                                                //有買賣動作之後，本期計算出未實現損益
                                                
                                                //NSLog(@"BS_last= %i",BS_last);
                                                if (BS_last  > 0 && enter_price_average>0) {
                                                    //做多未實現損益
                                                    profit_single_unrealize=(close-enter_price_average)/enter_price_average*1*100;
                                                    
                                                    last_trade_long_profitratio=profit_single_unrealize;
                                                }
                                                else if(BS_last  < 0 && enter_price_average>0){
                                                    //做空未實現損益
                                                    profit_single_unrealize=(close-enter_price_average)/enter_price_average*-1*100;
                                                    
                                                    last_trade_short_profitratio=profit_single_unrealize;
                                                    
                                                }
                                                else{
                                                    last_trade_long_profitratio=0;
                                                    last_trade_short_profitratio=0;
                                                    
                                                }
                                                
                                                
                                                //NSLog(@"last_trade_long_profitratio= %f",last_trade_long_profitratio);
                                                
                                                
                                                //停損機制
                                                //判斷是否需要停損
                                                if (isUse_Stop==1) {
                                                    
                                                    if (Stop_ratio*-100>last_trade_long_profitratio) {
                                                        //做多未實現損益超過停損率 下期停損掉
                                                        BS_Stop=-2;
                                                        
                                                        // NSLog(@"BS_Stop=-2 %f",enter_price);
                                                        // NSLog(@"slow=%f fast=%f",SlowLim,FastLim);
                                                        // NSLog(@"last_trade_long_profitratio=%f",last_trade_long_profitratio);
                                                        
                                                    }
                                                    else if (Stop_ratio*-100>last_trade_short_profitratio){
                                                        //做空未實現損益超過停損率 下期停損掉
                                                        BS_Stop=2;
                                                        
                                                    }
                                                    else{
                                                        BS_Stop=0;
                                                    }
                                                    
                                                }
                                                
                                                
                                                
                                                //3.年限
                                                NSDate *date_0;
                                                date_0=[his_dic_0 objectForKey:HIS_basic_date];
                                                
                                                NSDate  *date_now;
                                                date_now=[his_dic objectForKey:HIS_basic_date];
                                                
                                                double l;
                                                
                                                l=[date_now timeIntervalSinceDate:date_0]/86400;
                                                
                                                year=l/365;
                                                
                                                
                                                //4.報酬率
                                                {
                                                    //作多年化報酬率
                                                    return_long=realized_trade_long_profitratio_sum/year;
                                                    
                                                    //作空年化報酬率
                                                    return_short=realized_trade_short_profitratio_sum/year;
                                                    
                                                    //多空年化報酬率
                                                    return_ls=(realized_trade_long_profitratio_sum+realized_trade_short_profitratio_sum)/year;
                                                    
                                                }
                                                
                                            }
                                            
                                        }
                                        
                                        //5.儲存
                                        {
                                            
                                            //ma
                                            {
                                                
                                                
                                                
                                                [temp_cal setObject:[NSNumber numberWithDouble:ma_fast] forKey:HIS_dic_temp_MA_Fast];
                                                
                                                [temp_cal setObject:[NSNumber numberWithDouble:ma_slow] forKey:HIS_dic_temp_MA_Slow];
                                                
                                                [temp_cal setObject:[NSNumber numberWithBool:fastCrossSlow] forKey:HIS_dic_temp_MA_fastCrossSlow];
                                                
                                                
                                                
                                            }
                                            
                                            //基本資料mesa
                                            {
                                                [temp_cal setObject:[NSNumber numberWithDouble:price] forKey:HIS_dic_temp_price];
                                                [temp_cal setObject:[NSNumber numberWithDouble:Smooth] forKey:HIS_dic_temp_Smooth];
                                                [temp_cal setObject:[NSNumber numberWithDouble:Detrender] forKey:HIS_dic_temp_Detrender];
                                                [temp_cal setObject:[NSNumber numberWithDouble: Q1] forKey:HIS_dic_temp_Q1];
                                                [temp_cal setObject:[NSNumber numberWithDouble: l1] forKey:HIS_dic_temp_l1];
                                                [temp_cal setObject:[NSNumber numberWithDouble: jl] forKey:HIS_dic_temp_jl];
                                                [temp_cal setObject:[NSNumber numberWithDouble: jQ] forKey:HIS_dic_temp_jQ];
                                                [temp_cal setObject:[NSNumber numberWithDouble: l2] forKey:HIS_dic_temp_l2];
                                                [temp_cal setObject:[NSNumber numberWithDouble: Q2] forKey:HIS_dic_temp_Q2];
                                                [temp_cal setObject:[NSNumber numberWithDouble: Re] forKey:HIS_dic_temp_Re];
                                                [temp_cal setObject:[NSNumber numberWithDouble:lm] forKey:HIS_dic_temp_lm];
                                                [temp_cal setObject:[NSNumber numberWithDouble:Period] forKey:HIS_dic_temp_Period];
                                                [temp_cal setObject:[NSNumber numberWithDouble:SmoothPeriod] forKey:HIS_dic_temp_SmoothPeriod];
                                                [temp_cal setObject:[NSNumber numberWithDouble:Phase] forKey:HIS_dic_temp_Phase];
                                                [temp_cal setObject:[NSNumber numberWithDouble:DeltaPhase] forKey:HIS_dic_temp_DeltaPhase];
                                                
                                            }
                                            
                                            //基本資料
                                            {
                                                [temp_cal setObject:[NSNumber numberWithDouble:LF_bout] forKey:HIS_dic_temp_LF_bout];
                                                [temp_cal setObject:[NSNumber numberWithDouble:LF_sout] forKey:HIS_dic_temp_LF_sout];
                                                [temp_cal setObject:[NSNumber numberWithInt: LF_b] forKey:HIS_dic_temp_LF_b];
                                                [temp_cal setObject:[NSNumber numberWithInt: LF_s] forKey:HIS_dic_temp_LF_s];
                                                
                                                
                                            }
                                            
                                            //買賣訊號
                                            {
                                                [temp_cal setObject:[NSNumber numberWithDouble:BuyOrSell] forKey:CL_his_data_signal_LF_BS];
                                                
                                                [temp_cal setObject:[NSNumber numberWithDouble:Position_State] forKey:CL_his_data_signal_LF_State];
                                                
                                                
                                                //停損機制 最佳化
                                                [temp_cal setObject:[NSNumber numberWithDouble: BS_Stop] forKey:CL_his_data_signal_LF_BS_Stop];
                                                
                                            }
                                            
                                            //損益分析計算需要
                                            {
                                                //最後一筆買賣方向
                                                [temp_cal setObject:[NSNumber numberWithInt:BS_last] forKey:HIS_dic_temp_profit_bs];
                                                
                                               
                                                
                                                //最後一筆進場價位
                                                [temp_cal setObject:[NSNumber numberWithDouble:enter_price] forKey:HIS_dic_temp_profit_enterprice];
                                                
                                                //平均進場價位
                                                 //enter_price_average=99;
                                                
                                                [temp_cal setObject:[NSNumber numberWithDouble:enter_price_average] forKey:HIS_dic_temp_profit_enterprice_average];
                                                
                                                //是否有做多加碼
                                                [temp_cal setObject:[NSNumber numberWithBool:isAdd_long_step_count] forKey:HIS_dic_temp_profit_long_add];
                                                
                                                //是否有做空加碼
                                                [temp_cal setObject:[NSNumber numberWithBool:isAdd_short_step_count] forKey:HIS_dic_temp_profit_short_add];
                                                
                                                //摺疊次數
                                                [temp_cal setObject:[NSNumber numberWithInt:long_step_count] forKey:HIS_dic_temp_LFMESA_long_step_count];
                                                
                                                [temp_cal setObject:[NSNumber numberWithInt:short_step_count] forKey:HIS_dic_temp_LFMESA_short_step_cpont];
                                                
                                                
                                            }
                                            
                                            //損益
                                            {
                                                
                                                //單筆已經實現損益
                                                [temp_cal setObject:[NSNumber numberWithDouble:profit_single_realize] forKey:HIS_dic_temp_profit_single_realize];
                                                
                                                
                                                //單筆未實現損益
                                                [temp_cal setObject:[NSNumber numberWithDouble:profit_single_unrealize] forKey:HIS_dic_temp_profit_single_unrealize];
                                                
                                                
                                                
                                                //做多未實現損益
                                                [temp_cal setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF_longratio_lasttrade];
                                                //做空未實現損益
                                                [temp_cal setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF_shortratio_lasttrade];
                                                
                                                
                                                
                                                
                                                //做多已經實現損益合計
                                                [temp_cal setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF_longratio_realizedtrade_temp];
                                                //做空已經實現損益合計
                                                [temp_cal setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF_shortratio_realizedtrade_temp];
                                                
                                                
                                                //做多總交易次數
                                                [temp_cal setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF_long_total_count_temp];
                                                //做多賺錢次數
                                                [temp_cal setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF_long_win_count_temp];
                                                //做多勝率
                                                [temp_cal setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF_long_win_ratio_temp];
                                                
                                                
                                                //做空總交易次數
                                                [temp_cal setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF_short_total_count_temp];
                                                //做空賺錢次數
                                                [temp_cal setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF_short_win_count_temp];
                                                //做空勝率
                                                [temp_cal setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF_short_win_ratio_temp];
                                                
                                                
                                                
                                                //多空總交易次數
                                                [temp_cal setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF_LS_total_count_temp];
                                                //多空賺錢次數
                                                [temp_cal setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF_LS_win_count_temp];
                                                //多空勝率
                                                [temp_cal setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF_LS_win_ratio_temp];
                                                
                                                //做多最大獲利率
                                                [temp_cal setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF_long_max_gain_temp];
                                                
                                                
                                                
                                                //做多最大虧損率
                                                [temp_cal setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF_long_max_loss_temp];
                                                
                                                //做空最大獲利率
                                                [temp_cal setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF_short_max_gain_temp];
                                                
                                                //做空最大虧損率
                                                [temp_cal setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF_short_max_loss_temp];
                                                
                                                //多空最大獲利率
                                                [temp_cal setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF_LS_max_gain_temp  ];
                                                
                                                //多空最大虧損率
                                                [temp_cal setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF_LS_max_loss_temp];
                                                
                                                //作多年間
                                                [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_long_period_temp];
                                                //作空年間
                                                [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_short_period_temp];
                                                //多空年間
                                                [temp_cal setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_LS_period_temp];
                                                
                                                
                                                //作多年化報酬率
                                                [temp_cal setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF_long_return_temp];
                                                //作空年化報酬率
                                                [temp_cal setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF_short_return_temp];
                                                //多空年化報酬率
                                                [temp_cal setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF_LS_return_temp];
                                                
                                            }
                                            
                                        }
                                        
                                        
                                        
                                    }
                                    
                                    
                                    
                                    
                                }
                                
                                
                                
                            }
                            
                            //b.取出當筆損益的結果
                            {
                                //float longRatio=longRatio_start;
                                //float shortRatio=shortRatio_start;
                                //int longDay=longDay_start;
                                //int shortDay=shortDay_start;
                                NSMutableDictionary *opt_data=[[NSMutableDictionary alloc]init];
                                
                                //參數
                                [opt_data setObject:[NSNumber numberWithFloat: longRatio] forKey:@"longRatio"];
                                [opt_data setObject:[NSNumber numberWithFloat: shortRatio] forKey:@"shortRatio"];
                                [opt_data setObject:[NSNumber numberWithFloat: periodRatio] forKey:@"periodRatio"];
                                
                                
                                [opt_data setObject:[NSNumber numberWithInt: longDay] forKey:@"longDay"];
                                [opt_data setObject:[NSNumber numberWithInt: shortDay] forKey:@"shortDay"];
                                [opt_data setObject:[NSNumber numberWithInt: add_limit] forKey:@"add_limit"];
                                
                                
                                //計算損益結果
                                {
                                    
                                    //做多未實現損益
                                    [opt_data setObject:[NSNumber numberWithDouble:last_trade_long_profitratio] forKey:CL_his_data_profit_LF_longratio_lasttrade];
                                    //做空未實現損益
                                    [opt_data setObject:[NSNumber numberWithDouble:last_trade_short_profitratio] forKey:CL_his_data_profit_LF_shortratio_lasttrade];
                                    
                                    
                                    
                                    //做多勝率
                                    [opt_data setObject:[NSNumber numberWithDouble:long_win_ratio] forKey:CL_his_data_profit_LF_long_win_ratio_temp];
                                    
                                    //作多年化報酬率
                                    [opt_data setObject:[NSNumber numberWithDouble:return_long] forKey:CL_his_data_profit_LF_long_return_temp];
                                    
                                    //做多總交易次數
                                    [opt_data setObject:[NSNumber numberWithDouble:long_total_count] forKey:CL_his_data_profit_LF_long_total_count_temp];
                                    
                                    
                                    //做多已經實現損益合計
                                    [opt_data setObject:[NSNumber numberWithDouble:realized_trade_long_profitratio_sum] forKey:CL_his_data_profit_LF_longratio_realizedtrade_temp];
                                    //做空已經實現損益合計
                                    [opt_data setObject:[NSNumber numberWithDouble:realized_trade_short_profitratio_sum] forKey:CL_his_data_profit_LF_shortratio_realizedtrade_temp];
                                    
                                    
                                    
                                    //做多賺錢次數
                                    [opt_data setObject:[NSNumber numberWithDouble:long_win_count] forKey:CL_his_data_profit_LF_long_win_count_temp];
                                    
                                    
                                    
                                    //做空總交易次數
                                    [opt_data setObject:[NSNumber numberWithDouble:short_total_count] forKey:CL_his_data_profit_LF_short_total_count_temp];
                                    //做空賺錢次數
                                    [opt_data setObject:[NSNumber numberWithDouble:short_win_count] forKey:CL_his_data_profit_LF_short_win_count_temp];
                                    //做空勝率
                                    [opt_data setObject:[NSNumber numberWithDouble:short_win_ratio] forKey:CL_his_data_profit_LF_short_win_ratio_temp];
                                    
                                    
                                    
                                    //多空總交易次數
                                    [opt_data setObject:[NSNumber numberWithDouble:ls_total_count] forKey:CL_his_data_profit_LF_LS_total_count_temp];
                                    //多空賺錢次數
                                    [opt_data setObject:[NSNumber numberWithDouble:ls_win_count] forKey:CL_his_data_profit_LF_LS_win_count_temp];
                                    //多空勝率
                                    [opt_data setObject:[NSNumber numberWithDouble:ls_win_ratio] forKey:CL_his_data_profit_LF_LS_win_ratio_temp];
                                    
                                    //做多最大獲利率
                                    [opt_data setObject:[NSNumber numberWithDouble:long_max_gain] forKey:CL_his_data_profit_LF_long_max_gain_temp];
                                    
                                    
                                    
                                    //做多最大虧損率
                                    [opt_data setObject:[NSNumber numberWithDouble:long_max_loss] forKey:CL_his_data_profit_LF_long_max_loss_temp];
                                    
                                    //做空最大獲利率
                                    [opt_data setObject:[NSNumber numberWithDouble:short_max_gain] forKey:CL_his_data_profit_LF_short_max_gain_temp];
                                    
                                    //做空最大虧損率
                                    [opt_data setObject:[NSNumber numberWithDouble:short_max_loss] forKey:CL_his_data_profit_LF_short_max_loss_temp];
                                    
                                    //多空最大獲利率
                                    [opt_data setObject:[NSNumber numberWithDouble:ls_max_gain] forKey:CL_his_data_profit_LF_LS_max_gain_temp  ];
                                    
                                    //多空最大虧損率
                                    [opt_data setObject:[NSNumber numberWithDouble:ls_max_loss] forKey:CL_his_data_profit_LF_LS_max_loss_temp];
                                    
                                    //作多年間
                                    [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_long_period_temp];
                                    //作空年間
                                    [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_short_period_temp];
                                    //多空年間
                                    [opt_data setObject:[NSNumber numberWithDouble:year] forKey:CL_his_data_profit_LF_LS_period_temp];
                                    
                                    
                                    
                                    //作空年化報酬率
                                    [opt_data setObject:[NSNumber numberWithDouble:return_short] forKey:CL_his_data_profit_LF_short_return_temp];
                                    //多空年化報酬率
                                    [opt_data setObject:[NSNumber numberWithDouble:return_ls] forKey:CL_his_data_profit_LF_LS_return_temp];
                                    
                                    
                                    
                                    
                                    
                                    
                                }
                                
                                [optimize_data_dic addObject:opt_data];
                                [opt_data release];
                                
                                
                                
                            }
                            
                            //輸出到excel做檢查使用
                            if (NO) {
                                
                                //NSLog(@"his_dic_serial=%@",his_dic_serial );
                                
                                
                                //1.建立工作簿
                                RSworkBook * excel_book = [ [RSworkBook alloc] init];
                                excel_book.author = @"xxtradex";
                                excel_book.version = 1.2;
                                
                                //1.建立工作表sheet
                                RSworkSheet * sheet = [[RSworkSheet alloc] initWithName:@"明細"];
                                [excel_book addWorkSheet:sheet];
                                [sheet release];
                                
                                //3.標題列
                                {
                                    RSworkSheetRow * row_title = [[RSworkSheetRow alloc] initWithHeight:20];
                                    //該列高度
                                    row_title.height=20;
                                    
                                    //標題列cell 格式
                                    RSStyle *cell_style_title ;
                                    {
                                        
                                        cell_style_title = [[[RSStyle alloc] init] autorelease];
                                        cell_style_title.font = [NSFont fontWithName:@"新細明體" size:14];
                                        cell_style_title.size = 17;
                                        cell_style_title.color = [NSColor redColor];
                                        cell_style_title.alignmentH = RSStyleLeftAlign;
                                        cell_style_title.alignmentV = RSStyleCenterAlign;
                                        
                                        //cell 框線格式
                                        cell_style_title.gridlinestyle_Right=RSStyleGridContinuous;
                                        cell_style_title.gridlinestyle_Left=RSStyleGridContinuous;
                                        cell_style_title.gridlinestyle_Top=RSStyleGridContinuous;
                                        cell_style_title.gridlinestyle_Bottom=RSStyleGridDouble;
                                        
                                        //cell 框線寬度 注意：最大值不可以超過3
                                        cell_style_title.gridlinesWidth_Bottom=1;
                                        cell_style_title.gridlinesWidth_Left=1;
                                        cell_style_title.gridlinesWidth_Right=1;
                                        cell_style_title.gridlinesWidth_Top=1;
                                        
                                        
                                    }
                                    
                                    //該列內容
                                    {
                                        //cola:A
                                        [row_title addCellString:@"日期" withStyle:cell_style_title];
                                        
                                        //cola:B
                                        [row_title addCellString:@"收盤價" withStyle:cell_style_title];
                                        
                                        //cola:C
                                        [row_title addCellString:@"開盤價" withStyle:cell_style_title];
                                        
                                        //cola:D
                                        [row_title addCellString:@"多空狀態" withStyle:cell_style_title];
                                        
                                        //cola:E
                                        [row_title addCellString:@"多空訊號" withStyle:cell_style_title];
                                        
                                        //cola:F
                                        [row_title addCellString:@"停損" withStyle:cell_style_title];
                                        
                                        
                                        //cola:G
                                        [row_title addCellString:@"做多次數" withStyle:cell_style_title];
                                        
                                        //cola:H
                                        [row_title addCellString:@"做空次數" withStyle:cell_style_title];
                                        
                                        //cola:I
                                        [row_title addCellString:@"多出場" withStyle:cell_style_title];
                                        
                                        //cola:J
                                        [row_title addCellString:@"空出場" withStyle:cell_style_title];
                                        
                                        //cola:K
                                        [row_title addCellString:@"平均進場成本" withStyle:cell_style_title];
                                        
                                        //cola:L
                                        [row_title addCellString:@"是否有加碼動作" withStyle:cell_style_title];
                                        
                                        //cola:M
                                        [row_title addCellString:@"最後庫存部位多空" withStyle:cell_style_title];
                                        
                                        //cola:N
                                        [row_title addCellString:@"單筆已經實現損益" withStyle:cell_style_title];
                                        
                                        //cola:O
                                        [row_title addCellString:@"單筆未實現損益" withStyle:cell_style_title];
                                        
                                        //cola:O
                                        //[row_title addCellString:@"Period" withStyle:cell_style_title];
                                        
                                    }
                                    
                                    [sheet addWorkSheetRow:row_title];
                                    [row_title release];
                                }
                                
                                //4.內容格式
                                RSStyle *cell_style_content ;
                                {
                                    
                                    cell_style_content = [[[RSStyle alloc] init] autorelease];
                                    cell_style_content.font = [NSFont fontWithName:@"新細明體" size:14];
                                    cell_style_content.size = 14;
                                    cell_style_content.color = [NSColor redColor];
                                    cell_style_content.alignmentH = RSStyleLeftAlign;
                                    cell_style_content.alignmentV = RSStyleCenterAlign;
                                    
                                    //cell 框線格式
                                    cell_style_content.gridlinestyle_Right=RSStyleGridContinuous;
                                    cell_style_content.gridlinestyle_Left=RSStyleGridContinuous;
                                    cell_style_content.gridlinestyle_Top=RSStyleGridContinuous;
                                    cell_style_content.gridlinestyle_Bottom=RSStyleGridContinuous;
                                    
                                    //cell 框線寬度 注意：最大值不可以超過3
                                    cell_style_content.gridlinesWidth_Bottom=1;
                                    cell_style_content.gridlinesWidth_Left=1;
                                    cell_style_content.gridlinesWidth_Right=1;
                                    cell_style_content.gridlinesWidth_Top=1;
                                    
                                    
                                }
                                
                                //1.sheet 工作
                                {
                                    
                                    
                                    
                                    //該列內容
                                    {
                                        for (NSMutableDictionary *_dic in his_dic_serial) {
                                            
                                            //NSLog(@"%@",[_dic objectForKey:HIS_basic_date]);
                                            RSworkSheetRow * row_data = [[RSworkSheetRow alloc] initWithHeight:45];
                                            row_data.height=20;
                                            
                                            //cola:A 日期
                                            [row_data addCellString:[_dic objectForKey:HIS_basic_date]   withStyle:cell_style_content];
                                            
                                            
                                            //cola:B 收盤價
                                            [row_data addCellNumber: [[_dic objectForKey:HIS_basic_close] floatValue]   withStyle:cell_style_content];
                                            
                                            
                                            //cola:C 開盤價
                                            [row_data addCellNumber: [[_dic objectForKey:HIS_basic_open] floatValue]   withStyle:cell_style_content];
                                            
                                            
                                            
                                            //HIS_dic_signal
                                            {
                                                NSMutableDictionary *dic_HIS_optimize_temp=[_dic objectForKey:HIS_optimize_temp];
                                               
                                                //cola:D CL_his_data_signal_LF_State
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:CL_his_data_signal_LF_State] floatValue] ];
                                                
                                                //cola:E CL_his_data_signal_LF_BS
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:CL_his_data_signal_LF_BS] floatValue] ];
                                                
                                                //cola:F CL_his_data_signal_LF_BS_Stop
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:CL_his_data_signal_LF_BS_Stop] floatValue] ];
                                                
                                                
                                                
                                               
                                               
                                                //cola:G HIS_dic_temp_LFMESA_long_step_count
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_LFMESA_long_step_count] floatValue] ];
                                                
                                                //cola:H HIS_dic_temp_LFMESA_short_step_cpont
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_LFMESA_short_step_cpont] floatValue] ];
                                               
                                                
                                                //cola:G HIS_dic_temp_LFMESA_long_step_count
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_LF_bout] floatValue] ];
                                                
                                                //cola:H HIS_dic_temp_LFMESA_short_step_cpont
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_LF_sout] floatValue] ];
                                                
                                                
                                                
                                                
                                                //cola:I HIS_dic_temp_profit_enterprice_average
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_profit_enterprice_average] floatValue] ];
                                                
                                                //cola:J HIS_dic_temp_profit_long_add
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_profit_long_add] floatValue] ];
                                                
                                                //cola:J HIS_dic_temp_profit_bs
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_profit_bs] floatValue] ];
                                                
                                                
                                                //單筆已經實現損益
                                                 [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_profit_single_realize] floatValue] ];
                                                
                                                
                                                                                               
                                                //單筆未實現損益
                                                 [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_profit_single_unrealize] floatValue] ];
                                                                                               
                                                 //
                                                //Period
                                                [row_data addCellNumber: [[dic_HIS_optimize_temp objectForKey:HIS_dic_temp_Period] floatValue] ];
                                                
                                                
                                            }
                                            
                                            
                                            
                                            
                                            
                                            [sheet addWorkSheetRow:row_data];
                                            [row_data release];
                                        }
                                        
                                        
                                        
                                    }
                                    
                                    
                                    
                                }
                                
                                
                                //6.存檔
                                {
                                    //存入路徑
                                    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                                    NSString *documentsDir = [documentPaths objectAtIndex:0];
                                    
                                    NSString *BundleIdentifier;
                                    BundleIdentifier=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
                                    
                                    documentsDir=[documentsDir stringByAppendingPathComponent:BundleIdentifier];
                                    
                                    //寫入檔案
                                    [excel_book writeWithName:@"測試使用最佳化" toPath:documentsDir];
                                    [excel_book release];
                                    
                                    
                                    
                                }
                                
                                
                                
                                
                                
                                
                                
                            }
                            
                            //c.清除計算暫存記憶體 HIS_optimize_temp
                            for (NSMutableDictionary *his_dic in his_dic_serial) {
                                
                                NSDate *now=[his_dic objectForKey:HIS_basic_date];
                                
                                //判斷區間內
                                if ([now compare:start]==NSOrderedDescending  && [now compare:end]==NSOrderedAscending) {
                                    
                                    [his_dic removeObjectForKey:HIS_optimize_temp];
                                    
                                }
                                
                            }
                            
                            
                            [pool release];
                        }
                        
                        
                        
                    }
                    
                    
                    
                    
                }
            }
            
        }
             
        
        //3.針對計算結果排序 取出 mes1 LF2 LF3 參數
        //最佳化準則
        NSArray *sortedArray_final =nil;//最後排序結果
        {
            /* 選取最佳化參數原則：
             每檔股票參數的選取理論：因為有些股票的走勢只有走ㄧ大波,也許兩年才有依次大行情,
			 如果是以報酬率為先選擇標準,這樣會有偏誤,所以第一個是以勝率為準,這樣的話
			 系統比較穩定與客觀,之後則再以報酬率,交易次數為篩選標準,最後交易次數應該是
			 以越多交易次數越多越佳,主要還是避免幾次的大賺,雖然可能造成交易次數過多
             產業群組內,挑選哪檔股票當作程式交易的標準:以報酬率為優先考慮,主要是因為在參數篩選過程中
             已經先考慮到單次獲利太高的問題,且當然要選報酬率越高的股票當作標準
             */
            
            //NSLog(@"計算結果=%@",optimize_data_dic);
            NSString *sWin_ratio;
            NSString *sReturn;
            NSString *sCount;
            if (compare_method==0) {
                sWin_ratio=CL_his_data_profit_LF_long_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_long_return_temp;
                sCount=CL_his_data_profit_LF_long_total_count_temp;
            }
            else if (compare_method==1){
                sWin_ratio=CL_his_data_profit_LF_short_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_short_return_temp;
                sCount=CL_his_data_profit_LF_short_total_count_temp;
            }
            else if (compare_method==2){
                sWin_ratio=CL_his_data_profit_LF_LS_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_LS_return_temp;
                sCount=CL_his_data_profit_LF_LS_total_count_temp;
            }
            else{
                sWin_ratio=CL_his_data_profit_LF_LS_win_ratio_temp;
                sReturn=CL_his_data_profit_LF_LS_return_temp;
                sCount=CL_his_data_profit_LF_LS_total_count_temp;
            }
            
            //NSLog(@"比較準則=%i %@ %@ %@",compare_method,sWin_ratio,sReturn,sCount);
            
            //特別排序產生有加碼的最佳化參數
            if (isCreate_Add_Limit_Para) {
                NSLog(@"特別排序產生有加碼的最佳化參數");
                //取出排序完後得結果上限
                int max_sort_count ; //取出前5%
                int max_sort_count_half ;//取出前2.5%
                int max_sort_count_half_half ;//取出前1%
                {
                    if ((int)([optimize_data_dic count]*0.05)>1) {
                        max_sort_count=(int)([optimize_data_dic count]*0.05);
                    }
                    else{
                        max_sort_count=1;
                    }
                    
                    if ((int)([optimize_data_dic count]*0.025)>1) {
                        max_sort_count_half=(int)([optimize_data_dic count]*0.025);
                    }
                    else{
                        max_sort_count_half=1;
                    }
                    if ((int)([optimize_data_dic count]*0.01)>1) {
                        max_sort_count_half_half=(int)([optimize_data_dic count]*0.01);
                    }
                    else{
                        max_sort_count_half_half=1;
                    }
                    
                    
                }
                
                
                //1.針對 "參數-加碼量@"add_limit"" 排序-大到小
                NSArray *sortedArray_add_limit =nil;
                sortedArray_add_limit= [ optimize_data_dic  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:@"add_limit"] ;
                    NSNumber *lastName2 = [secondObject objectForKey:@"add_limit"] ;
                    
                    return [lastName2 compare: lastName1];
                    
                }];
                
                //2..報酬率 排序-大到小
                NSArray *sortedArray_return_ratio =nil;
                sortedArray_return_ratio= [sortedArray_add_limit  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:sReturn] ;
                    NSNumber *lastName2 = [secondObject objectForKey:sReturn] ;
                    
                    return [lastName2 compare: lastName1];
                    
                }];
                
                //3.取出報酬率排序前max_sort_count名的
                NSMutableArray *sortReturnPercentage_top;
                int top_win_ratio;
                {
                    if ([sortedArray_return_ratio count]<max_sort_count) {
                        top_win_ratio=[sortedArray_return_ratio count];
                    }
                    else{
                        top_win_ratio=max_sort_count;
                    }
                    
                }
                sortReturnPercentage_top=[[NSMutableArray alloc] init];
                for (int k=0 ; k<top_win_ratio ; k++) {
                    [sortReturnPercentage_top addObject: [sortedArray_return_ratio objectAtIndex:k ]  ];
                }
                
                //4.依照年報酬率排序-大到小
                NSArray *sortedArray_win =nil;
                sortedArray_win= [ sortReturnPercentage_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:sWin_ratio] ;
                    NSNumber *lastName2 = [secondObject objectForKey:sWin_ratio] ;
                    //sWin_ratio
                    return [lastName2 compare: lastName1];
                    
                }];
                
                //5.取出年報酬率前max_sort_count_half名的
                NSMutableArray *sortWin_top;
                int top_return ;
                {
                    if ([sortedArray_win count]<max_sort_count_half) {
                        top_return=[sortedArray_win count];
                    }
                    else{
                        top_return=max_sort_count_half;
                    }
                    
                }
                
                sortWin_top=[[NSMutableArray alloc] init];
                for (int k=0 ; k< top_return ; k++) {
                    [sortWin_top addObject: [sortedArray_win objectAtIndex:k ]  ];
                }
                
                
                //6.對交易次數排序 改以最少次數為最佳- 小到大
                NSArray *sortedArray_count;
                sortedArray_count= [ sortWin_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:sCount] ;
                    NSNumber *lastName2 = [secondObject objectForKey:sCount] ;
                    
                    return [lastName1 compare: lastName2];
                    
                }];
                
                //7.取出交易次數最少的前1%
                NSMutableArray *sortCount_top;
                int top_count ;
                {
                    if ([sortedArray_count count]<max_sort_count_half_half) {
                        top_count=[sortedArray_count count];
                    }
                    else{
                        top_count=max_sort_count_half_half;
                    }
                    
                }
                sortCount_top=[[NSMutableArray alloc] init];
                for (int k=0 ; k< top_count ; k++) {
                    [sortCount_top addObject: [sortedArray_count objectAtIndex:k ]  ];
                }
                
                //8.針對加碼次數多的排序-大到小
                sortedArray_final= [ sortCount_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:@"add_limit"] ;
                    NSNumber *lastName2 = [secondObject objectForKey:@"add_limit"] ;
                    
                    return [lastName2 compare: lastName1];
                    
                }];
                
                [sortWin_top release];
                [sortReturnPercentage_top release];
                [sortCount_top release];
                
                
            }
            //一般排序產生最佳化參數
            else{
                 NSLog(@"一般排序產生最佳化參數");
                //a.勝率排序
                int max_sort_count ; //取出前10%
                int max_sort_count_half ;//取出前5%
                {
                    if ((int)([optimize_data_dic count]*0.1)>1) {
                        max_sort_count=(int)([optimize_data_dic count]*0.1);
                    }
                    else{
                        max_sort_count=1;
                    }
                    
                    if ((int)([optimize_data_dic count]*0.05)>1) {
                        max_sort_count_half=(int)([optimize_data_dic count]*0.05);
                    }
                    else{
                        max_sort_count_half=1;
                    }
                    
                    
                    
                }
                
                
                
                NSArray *sortedArray_win_ratio =nil;
                sortedArray_win_ratio= [ optimize_data_dic  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:sWin_ratio] ;
                    NSNumber *lastName2 = [secondObject objectForKey:sWin_ratio] ;
                    
                    return [lastName2 compare: lastName1];
                    
                }];
                
                //b.取出勝率前max_sort_count名的
                NSMutableArray *sortWinPercentage_top;
                int top_win_ratio;
                {
                    if ([sortedArray_win_ratio count]<max_sort_count) {
                        top_win_ratio=[sortedArray_win_ratio count];
                    }
                    else{
                        top_win_ratio=max_sort_count;
                    }
                    
                }
                sortWinPercentage_top=[[NSMutableArray alloc] init];
                for (int k=0 ; k<top_win_ratio ; k++) {
                    [sortWinPercentage_top addObject: [sortedArray_win_ratio objectAtIndex:k ]  ];
                }
                
                //c.依照年報酬率排序
                
                NSArray *sortedArray_return =nil;
                sortedArray_return= [ sortWinPercentage_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:sReturn] ;
                    NSNumber *lastName2 = [secondObject objectForKey:sReturn] ;
                    
                    return [lastName2 compare: lastName1];
                    
                }];
                
                //d.取出年報酬率前15名的
                NSMutableArray *sortReturn_top;
                int top_return ;
                {
                    if ([sortedArray_return count]<max_sort_count_half) {
                        top_return=[sortedArray_return count];
                    }
                    else{
                        top_return=max_sort_count_half;
                    }
                    
                }
                sortReturn_top=[[NSMutableArray alloc] init];
                for (int k=0 ; k< top_return ; k++) {
                    [sortReturn_top addObject: [sortedArray_return objectAtIndex:k ]  ];
                }
                
                
                //e.對交易次數排序 改以最少次數為最佳
                
                sortedArray_final= [ sortReturn_top  sortedArrayUsingComparator:^(id firstObject, id secondObject) {
                    
                    NSNumber *lastName1 = [firstObject objectForKey:sCount] ;
                    NSNumber *lastName2 = [secondObject objectForKey:sCount] ;
                    
                    return [lastName1 compare: lastName2];
                    
                }];
                
                [sortWinPercentage_top release];
                [sortReturn_top release];
                
            }
                        
             
            
            if (YES) {
                /*
                 "CL_his_data_profit_LF_long_max_gain_temp" = "12.06142948095875";
                 "CL_his_data_profit_LF_long_max_loss_temp" = 0;
                 "CL_his_data_profit_LF_long_period_temp" = "1.542465753424658";
                 "CL_his_data_profit_LF_long_return_temp" = "22.27070360710831";
                 "CL_his_data_profit_LF_long_total_count_temp" = 3;
                 "CL_his_data_profit_LF_long_win_count_temp" = 3;
                 "CL_his_data_profit_LF_long_win_ratio_temp" = 100;
                 "CL_his_data_profit_LF_longratio_lasttrade" = 0;
                 "CL_his_data_profit_LF_longratio_realizedtrade_temp" = "34.35179761863556";
                 
                 "add_limit" = 1;
                 longDay = 22;
                 longRatio = "0.4";
                 periodRatio = "1.3";
                 shortDay = 22;
                 shortRatio = "0.4";
                 
                 
                 */
                
                
                
                
                
                //NSLog(@"sortedArray_win_ratio=%@",sortedArray_win_ratio);
                {
                    
                    //NSLog(@"his_dic_serial=%@",his_dic_serial );
                    
                    
                    //1.建立工作簿
                    RSworkBook * excel_book = [ [RSworkBook alloc] init];
                    excel_book.author = @"xxtradex";
                    excel_book.version = 1.2;
                    
                    //1.建立工作表sheet
                    RSworkSheet * sheet = [[RSworkSheet alloc] initWithName:@"明細"];
                    [excel_book addWorkSheet:sheet];
                    [sheet release];
                    
                    //3.標題列
                    {
                        RSworkSheetRow * row_title = [[RSworkSheetRow alloc] initWithHeight:20];
                        //該列高度
                        row_title.height=20;
                        
                        //標題列cell 格式
                        RSStyle *cell_style_title ;
                        {
                            
                            cell_style_title = [[[RSStyle alloc] init] autorelease];
                            cell_style_title.font = [NSFont fontWithName:@"新細明體" size:14];
                            cell_style_title.size = 17;
                            cell_style_title.color = [NSColor redColor];
                            cell_style_title.alignmentH = RSStyleLeftAlign;
                            cell_style_title.alignmentV = RSStyleCenterAlign;
                            
                            //cell 框線格式
                            cell_style_title.gridlinestyle_Right=RSStyleGridContinuous;
                            cell_style_title.gridlinestyle_Left=RSStyleGridContinuous;
                            cell_style_title.gridlinestyle_Top=RSStyleGridContinuous;
                            cell_style_title.gridlinestyle_Bottom=RSStyleGridDouble;
                            
                            //cell 框線寬度 注意：最大值不可以超過3
                            cell_style_title.gridlinesWidth_Bottom=1;
                            cell_style_title.gridlinesWidth_Left=1;
                            cell_style_title.gridlinesWidth_Right=1;
                            cell_style_title.gridlinesWidth_Top=1;
                            
                            
                        }
                        
                        //該列內容
                        {
                            //cola:A
                            [row_title addCellString:@"add_limit" withStyle:cell_style_title];
                            
                            //cola:B
                            [row_title addCellString:@"longRatio" withStyle:cell_style_title];
                            
                            //cola:C
                            [row_title addCellString:@"shortRatio" withStyle:cell_style_title];
                            
                            //cola:D
                            [row_title addCellString:@"periodRatio" withStyle:cell_style_title];
                            
                            //cola:E
                            [row_title addCellString:@"CL_his_data_profit_LF_long_win_ratio_temp" withStyle:cell_style_title];
                            
                            //cola:F
                            [row_title addCellString:@"CL_his_data_profit_LF_long_return_temp" withStyle:cell_style_title];
                            
                            
                            //cola:G
                            [row_title addCellString:@"CL_his_data_profit_LF_long_total_count_temp" withStyle:cell_style_title];
                            
                            //cola:H
                            [row_title addCellString:@"做空次數" withStyle:cell_style_title];
                            
                            //cola:I
                            [row_title addCellString:@"多出場" withStyle:cell_style_title];
                            
                            //cola:J
                            [row_title addCellString:@"空出場" withStyle:cell_style_title];
                            
                            //cola:K
                            [row_title addCellString:@"平均進場成本" withStyle:cell_style_title];
                            
                            //cola:L
                            [row_title addCellString:@"是否有加碼動作" withStyle:cell_style_title];
                            
                            //cola:M
                            [row_title addCellString:@"最後庫存部位多空" withStyle:cell_style_title];
                            
                            //cola:N
                            [row_title addCellString:@"單筆已經實現損益" withStyle:cell_style_title];
                            
                            //cola:O
                            [row_title addCellString:@"單筆未實現損益" withStyle:cell_style_title];
                            
                            //cola:O
                            //[row_title addCellString:@"Period" withStyle:cell_style_title];
                            
                        }
                        
                        [sheet addWorkSheetRow:row_title];
                        [row_title release];
                    }
                    
                    //4.內容格式
                    RSStyle *cell_style_content ;
                    {
                        
                        cell_style_content = [[[RSStyle alloc] init] autorelease];
                        cell_style_content.font = [NSFont fontWithName:@"新細明體" size:14];
                        cell_style_content.size = 14;
                        cell_style_content.color = [NSColor redColor];
                        cell_style_content.alignmentH = RSStyleLeftAlign;
                        cell_style_content.alignmentV = RSStyleCenterAlign;
                        
                        //cell 框線格式
                        cell_style_content.gridlinestyle_Right=RSStyleGridContinuous;
                        cell_style_content.gridlinestyle_Left=RSStyleGridContinuous;
                        cell_style_content.gridlinestyle_Top=RSStyleGridContinuous;
                        cell_style_content.gridlinestyle_Bottom=RSStyleGridContinuous;
                        
                        //cell 框線寬度 注意：最大值不可以超過3
                        cell_style_content.gridlinesWidth_Bottom=1;
                        cell_style_content.gridlinesWidth_Left=1;
                        cell_style_content.gridlinesWidth_Right=1;
                        cell_style_content.gridlinesWidth_Top=1;
                        
                        
                    }
                    
                    //1.sheet 工作
                    {
                        
                        
                        
                        //該列內容
                        {
                            for (NSMutableDictionary *_dic in sortedArray_final) {
                                
                                
                                RSworkSheetRow * row_data = [[RSworkSheetRow alloc] initWithHeight:45];
                                row_data.height=20;
                                
                                //cola:A add_limit
                                [row_data addCellNumber: [[_dic objectForKey:@"add_limit"] intValue]   withStyle:cell_style_content];
                                
                                
                                //cola:B longRatio
                                [row_data addCellNumber: [[_dic objectForKey:@"longRatio"] floatValue]   withStyle:cell_style_content];
                                
                                
                                //cola:C shortRatio
                                [row_data addCellNumber: [[_dic objectForKey:@"shortRatio"] floatValue]   withStyle:cell_style_content];
                                
                                //cola:D periodRatio
                                [row_data addCellNumber: [[_dic objectForKey:@"periodRatio"] floatValue]   withStyle:cell_style_content];
                                
                                //cola:E CL_his_data_profit_LF_long_win_ratio_temp
                                [row_data addCellNumber: [[_dic objectForKey: CL_his_data_profit_LF_long_win_ratio_temp ] floatValue]   withStyle:cell_style_content];
                                
                                //cola:F CL_his_data_profit_LF_long_return_temp
                                [row_data addCellNumber: [[_dic objectForKey: CL_his_data_profit_LF_long_return_temp ] floatValue]   withStyle:cell_style_content];
                                
                                //cola:G CL_his_data_profit_LF_long_total_count_temp
                                [row_data addCellNumber: [[_dic objectForKey: CL_his_data_profit_LF_long_total_count_temp ] floatValue]   withStyle:cell_style_content];
                                
                                
                                
                                
                                
                                [sheet addWorkSheetRow:row_data];
                                [row_data release];
                            }
                            
                            
                            
                        }
                        
                        
                        
                    }
                    
                    
                    //6.存檔
                    {
                        //存入路徑
                        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                        NSString *documentsDir = [documentPaths objectAtIndex:0];
                        
                        NSString *BundleIdentifier;
                        BundleIdentifier=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
                        
                        documentsDir=[documentsDir stringByAppendingPathComponent:BundleIdentifier];
                        
                        //寫入檔案
                        [excel_book writeWithName:@"測試使用最佳化 參數" toPath:documentsDir];
                        [excel_book release];
                        
                        
                        
                    }
                    
                    
                    
                    
                    
                    
                    
                }
                
                
                
                
                
                
                
                
            }
            
          
            
          
            
        }
        
        //4.儲存最佳化後的參數
        {
            NSLog(@"排序循環數目 =%i",count_loop);
            //NSLog(@"排序結果 =%@",sortedArray_count_final);
            
            int middle=[sortedArray_final count]/2;
            NSMutableDictionary *dic1=[sortedArray_final objectAtIndex:0];
            NSMutableDictionary *dic2=[sortedArray_final objectAtIndex:middle];
            NSMutableDictionary *dic3= [sortedArray_final objectAtIndex:[sortedArray_final count]-1];
            
            // NSLog(@"mesa1=%@",dic1);
            // NSLog(@"mesa2=%@",dic2);
            // NSLog(@"mesa3=%@",dic3);
            
            //存入日的週期的參數資料庫內
            NSString *DWM=day;
            
            //LF1
            {
                NSMutableDictionary *para_value_dic1=[[[NSMutableDictionary alloc]init ] autorelease];
                float  slongRatio1,sshortRatio1,speriodRatio1;
                int    slongDay1,sshortDay1;
                int    add_limit_1;
                
                slongRatio1= [[dic1 objectForKey:@"longRatio"] doubleValue];
                sshortRatio1=[[dic1 objectForKey:@"shortRatio"] doubleValue];
                speriodRatio1=[[dic1 objectForKey:@"periodRatio"] doubleValue];
                
                slongDay1=   [[dic1 objectForKey:@"longDay"] doubleValue];
                sshortDay1=  [[dic1 objectForKey:@"shortDay"] doubleValue];
                add_limit_1=  [[dic1 objectForKey:@"add_limit"] doubleValue];
                
                
                
                [para_value_dic1 setObject:[NSNumber numberWithFloat:slongRatio1] forKey:Para_1];
                [para_value_dic1 setObject:[NSNumber numberWithFloat:sshortRatio1] forKey:Para_2];
                [para_value_dic1 setObject:[NSNumber numberWithFloat:speriodRatio1] forKey:Para_3];
                [para_value_dic1 setObject:[NSNumber numberWithFloat:add_limit_1] forKey:Para_4];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic1 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic1 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic1 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_LFMESA1 Para_dic:para_value_dic1 period:DWM];
            }
            
            //LF2
            {
                NSMutableDictionary *para_value_dic2=[[[NSMutableDictionary alloc]init ] autorelease];
                float  slongRatio2,sshortRatio2,speriodRatio2;
                int    slongDay2,sshortDay2;
                int    add_limit_2;
                
                
                slongRatio2=[[dic2 objectForKey:@"longRatio"] doubleValue];
                sshortRatio2=[[dic2 objectForKey:@"shortRatio"] doubleValue];
                speriodRatio2=[[dic2 objectForKey:@"periodRatio"] doubleValue];
                
                slongDay2=[[dic2 objectForKey:@"longDay"] doubleValue];
                sshortDay2=[[dic2 objectForKey:@"shortDay"] doubleValue];
                 add_limit_2=  [[dic2 objectForKey:@"add_limit"] doubleValue];
                
                
                [para_value_dic2 setObject:[NSNumber numberWithFloat:slongRatio2] forKey:Para_1];
                [para_value_dic2 setObject:[NSNumber numberWithFloat:sshortRatio2] forKey:Para_2];
                [para_value_dic2 setObject:[NSNumber numberWithFloat:speriodRatio2] forKey:Para_3];
                [para_value_dic2 setObject:[NSNumber numberWithFloat:add_limit_2] forKey:Para_4];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic2 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic2 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic2 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_LFMESA2 Para_dic:para_value_dic2 period:DWM];
            }
            
            //LF3
            {
                NSMutableDictionary *para_value_dic3=[[[NSMutableDictionary alloc]init ] autorelease];
                float  slongRatio3,sshortRatio3,speriodRatio3;
                int    slongDay3,sshortDay3;
                int    add_limit_3;
                
                
                slongRatio3=[[dic3 objectForKey:@"longRatio"] doubleValue];
                sshortRatio3=[[dic3 objectForKey:@"shortRatio"] doubleValue];
                speriodRatio3=[[dic3 objectForKey:@"periodRatio"] doubleValue];
                
                
                slongDay3=[[dic3 objectForKey:@"longDay"] doubleValue];
                sshortDay3=[[dic3 objectForKey:@"shortDay"] doubleValue];
                 add_limit_3=  [[dic3 objectForKey:@"add_limit"] doubleValue];
                
                
                [para_value_dic3 setObject:[NSNumber numberWithFloat:slongRatio3] forKey:Para_1];
                [para_value_dic3 setObject:[NSNumber numberWithFloat:sshortRatio3] forKey:Para_2];
                [para_value_dic3 setObject:[NSNumber numberWithFloat:speriodRatio3] forKey:Para_3];
                [para_value_dic3 setObject:[NSNumber numberWithFloat:add_limit_3] forKey:Para_4];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:0] forKey:Para_5];
                
                //停損機制
                [para_value_dic3 setObject:[NSNumber numberWithDouble:long_cost] forKey:Para_Optimize_long_cost];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:short_cost] forKey:Para_Optimize_short_cost];
                [para_value_dic3 setObject:[NSNumber numberWithDouble:Stop_ratio] forKey:Para_Optimize_Stop_ratio];
                [para_value_dic3 setObject:[NSNumber numberWithInt:isUse_Stop] forKey:Para_Optimize_isUse_Stop];
                
                [[self data_object_para] Save_Para: Defaults_Calculate_LFMESA3 Para_dic:para_value_dic3 period:DWM];
            }
            
            
            
        }
        
        //5.重算資料
        {
            
            //NSLog(@"參數最佳化後，重新計算所有資料");
            //重新計算內存數據
            [self re_calculate_history_indicator_signal];
            
            //報價表更新
            // NSLog(@"最佳化成功 但是尚未完成重新顯示走勢圖或表格 的更新");
            
            
            //公告最佳化個股結束
            {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                
                [dict setObject:self forKey:@"dataobject"];
                
                NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:NOT_sheet_para_optimize_finize
                                  object:self
                                userInfo: dict   ];
                
            }
            
            
            
            
        }
        
        //6.清除每筆計算結果資料
        [optimize_data_dic release];    }
}



#pragma mark -
#pragma mark NSCoder

- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    [aCoder encodeObject:his_data_get_date forKey:@"Data_Object_his_data_get_date"];
    [aCoder encodeObject:his_data_serial forKey:@"Data_Object_his_data_serial"];
    [aCoder encodeObject:his_data_high forKey:@"Data_Object_his_data_high"];
    [aCoder encodeObject:his_data_low forKey:@"Data_Object_his_data_low"];
    [aCoder encodeObject:table_data forKey:@"Data_Object_table_data"];
   
    
    
}
- (id)initWithCoder:(NSCoder *)aDecoder{
    self=[super init];
    if (self) {
        
        
        his_data_get_date= [[aDecoder decodeObjectForKey:@"Data_Object_his_data_get_date"] retain]  ;
        his_data_serial= [[aDecoder decodeObjectForKey:@"Data_Object_his_data_serial"] retain] ;
       
        his_data_high=[ [aDecoder decodeObjectForKey:@"Data_Object_his_data_high"] retain]  ;
        his_data_low= [[aDecoder decodeObjectForKey:@"Data_Object_his_data_low"] retain] ;
        table_data= [[aDecoder decodeObjectForKey:@"Data_Object_table_data"] retain]  ;
      
    }
    return self;
}

@end
